Understanding Type Erasure in Java Generics
When working with Java generics, you might notice a peculiar behavior: while generics enable compile-time type safety, their type information seems to disappear at runtime. This disappearance, called type erasure, is a fundamental concept in Java...

public class GenericBox<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
public class GenericBox {
private Object item;
public void setItem(Object item) {
this.item = item;
}
public Object getItem() {
return item;
}
}
List<String> stringList = new ArrayList<>();
List<Integer> integerList = new ArrayList<>();
if (stringList.getClass() == integerList.getClass()) {
System.out.println("Both lists are of the same type at runtime.");
}
Both lists are of the same type at runtime.
List<String> list = new ArrayList<>();
list.add("Java");
String item = list.get(0); // No explicit cast at compile time
List list = new ArrayList();
list.add("Java");
String item = (String) list.get(0); // Explicit cast at runtime
List<int> numbers = new ArrayList<>(); // Compilation error
List<Integer> numbers = new ArrayList<>();
T[] array = new T[10]; // Compilation error
@SuppressWarnings("unchecked")
T[] array = (T[]) new Object[10];
public void process(List<String> list) { }
public void process(List<Integer> list) { } // Compilation error
public void process(List list) { }
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
public class GenericType<T> {
public void printType() {
Type superclass = getClass().getGenericSuperclass();
if (superclass instanceof ParameterizedType) {
Type[] typeArgs = ((ParameterizedType) superclass).getActualTypeArguments();
for (Type type : typeArgs) {
System.out.println("Type argument: " + type.getTypeName());
}
}
}
}
Type argument: java.lang.String
public void printList(List<?> list) {
for (Object item : list) {
System.out.println(item);
}
}
public class TypeSafeBox<T> {
private T item;
public void setItem(T item) {
this.item = item;
}
public T getItem() {
return item;
}
}
Read more at : Understanding Type Erasure in Java Generics
About the author
I am Tuanh.net. As of 2024, I have accumulated 8 years of experience in backend programming. I am delighted to connect and share my knowledge with everyone.
Comments
Join the discussionNo comments yet. Be the first to comment.





