Type Erasure

Quick Reference :

  • Type Parameter is applicable only at Compile Time and Not at Runtime
  • During Compilation i.e conversion to .class file the Generics are removed hence called TypeErasure

  • In order to implement generics, java uses type erasure.
  • Replace all type parameters in generic types with their bounds or objects.
  • If the type parameters are unbounded then the final bytecode will contain plain java objects/classes.
  • Uses type casts if necessary.
  • Sometimes java generates extra methods so called bridge methods in order to maintain polymorphism with generics type.

Example of Code conversion :

List<Integer> list = new ArrayList<>();
list.add(3);
Integer num = list.get(0);

Above code is converted into bytecode i.e class file which looks like below :

List list = new ArrayList();
list.add(3);
Integer num = (Integer) list.get(0);

Now lets see how type T is converted in below code:

public class Demo<T> {
	private T item;

	public T getItem() {
		return item;
	}

	public void setItem(T item) {
		this.item = item;
	}
}

Above code is converted into

public class Demo {
	private Object item;

	public Object getItem() {
		return item;
	}

	public void setItem(Object item) {
		this.item = item;
	}
}

Leave a Comment