What is type Erasure?

Generics in Java provide type checking at compile time and it has nothing to do at runtime. Java compiler uses Type Erasure feature to remove all generics type checking code (replace it with bound or Object if the type parameters are unbounded) in bytecode, insert type casting if necessary and generate bridge methods to preserve polymorphism in extended generic types.

Here is an example of generic a class:

class TypeErasureExample {
private T t;

public TypeErasureExample(T t) {
this.t = t;
}

public T getT() {
return t;
}
}

After compilation the type will be replaced with String as follows:

class TypeErasureExample {
private String t;

public TypeErasureExample(String t) {
this.t = t;
}

public String getT() {
return t;
}
}

Type erasure at class or class variable level:
At the class level, type parameters on the class are removed at compile time and replaced with its first bound or Object if the type parameter is unbound.
Here are few examples:
Type erasure when type parameter is unbound:

class TypeErasureUnboundExample {
private T t;

public TypeErasureUnboundExample(T t) {
this.t = t;
}

public T getT() {
return t;
}
}

After compilation the type will be replace with Object (because type parameter is unbound) as follows:

class TypeErasureUnboundExample {
private Object t;

public TypeErasureUnboundExample(Obhect t) {
this.t = t;
}

public Object getT() {
return t;
}
}

Type erasure when type parameter is bound:

class TypeErasureExample {
private T t;

public TypeErasureExample(T t) {
this.t = t;
}

public T getT() {
return t;
}
}

After compilation the type will be replaced with String (with first bound) as follows:

class TypeErasureExample {
private String t;

public TypeErasureExample(String t) {
this.t = t;
}

public String getT() {
return t;
}
}

Type Erasure at method level:
Method type parameters are converted to its parent type Object if its unbound or its bound class when its bound:

For example:
If type parameter is unbounded:

public static  void genericMethod(T t){
System.out.println(t);
}

Will be converted to following at compile time:

public static void genericMethod(Object t){
System.out.println(t);
}

If type parameter is bounded:

public static  void genericMethod(T t){
System.out.println(t);
}

Will be converted to following at compile time:

public static void genericMethod(String t){
System.out.println(t);
}

Related Articles

Leave a Reply

Be the First to Comment!

avatar