TypeErasure in Java

The concept of Generic has been introduced in the Java language in order to facilitate tighter checks of types at the compile time and to support generic programming. In order to implement generics, the compiler of Java applies the type erasure to:

  1. Replacing all parameters type in the generic types with the bounds or Object when the type of the parameters is not bounded. The generated bytecode, hence, only contains the ordinary methods, interfaces, and classes.
  2. Inserting the type casts if required in order to support the type safety.
  3. Generating the bridge methods for preserving polymorphism in generic types that are extended.

Generally, generic code that is compiled just utilizes the java.lang.Object whenever one talks about P (or some different type parameter) - and there is some information (metadata), which tells the Java compiler that it is a generic type. Whenever one compiles the code against the method or generic type, the Java compiler deciphers what the person really means (that is, the compiler finds out the type argument for P) and validates at the compile-time that one is doing the correct thing or not. However, the code that is emitted again does talk in terms of the java.lang.Object - the Java compiler produces the extra casts where needed. At the execution time, a List and a List are the same. The Java compiler erases the extra type information.

After the compilation, the type parameter P is replaced by the default Object. Observe the following program.

Let's take another example, where the type parameter P extends the java.lang.String class.

After the compilation, we get

Implementation of TypeErasure

Let's see an example of the implementation of TypeErasure.

FileName: TypeErasure2.java

Output:

Hello
World

Explanation: Here, when the code is compiled, no warning is issued by the compiler. It is due to Type Erasure.

Now, observe the following program.

FileName: TypeErasure3.java

When we compile the above program using the javac command, we get the following warning. It is because of the type erasure as it is not mentioned in the program about the type of list that is being used.

Note: TypeErasure3.java uses unchecked or unsafe operations. Recompile with -Xlint:unchecked for details.

Output still remains the same.

Output:

Hello
World





Latest Courses