· · ─ ·✶· ─ · ·
Type erasure is Java’s way of implementing generics without actually keeping generic type information at runtime.
So Java has generics only at compile time and not at runtime. Why? We’ll get to that.
After compilation, Java “erases” the type parameters and converts them into ordinary non-generic types.
List<Integer>
List<String>
List<Double>becomes
Listat runtime.
So back to why?
Back when generics were added in Java 5, there was already a massive ecosystem of old Java code using things like:
List list = new ArrayList();Java wanted:
- old code to still work
- libraries to remain compatible
So instead of creating “real” runtime generics like C# does, Java added generics mostly as a compile-time feature.
That design decision is why we have type erasure.
Some Consequences of Type Erasure:
List<String> a = new ArrayList<String>();
List<Integer> b = new ArrayList<Integer>();
System.out.println(a.getClass() == b.getClass());prints True even though with the generic type they would be different.
But due to type erasure, both are just ArrayList at runtime.
Type erasure also explains why we cannot do:
if (obj instanceof List<String>)Compile error.
The JVM cannot check for String because that information no longer exists.
We can only do:
if (obj instanceof List)· · ─ ·✶· ─ · ·