Advertisement
Intermediate Java, Generics

What is type erasure, and how does it explain why generic type information is unavailable at runtime (e.g., why you can't do `if (obj instanceof List<String>)`)?

Short answer

Type erasure means the compiler uses generic type parameters ONLY for compile-time type checking, then removes (erases) them from the compiled bytecode, replacing an unbounded type parameter with Object (or its bound, if bounded) and inserting the necessary casts automatically…

Save Java mock interview
Advertisement
AModel answer
Type erasure means the compiler uses generic type parameters ONLY for compile-time type checking, then removes (erases) them from the compiled bytecode, replacing an unbounded type parameter with Object (or its bound, if bounded) and inserting the necessary casts automatically -- this backward-compatibility-motivated design (letting generic code interoperate with pre-generics bytecode) means a List<String> and a List<Integer> are actually represented by the IDENTICAL class (List) at runtime, with no way to distinguish them via reflection or instanceof, which is why `obj instanceof List<String>` is illegal (only the unparameterized `obj instanceof List` is allowed).
List<String> stringList = new ArrayList<>();
List<Integer> intList = new ArrayList<>();

System.out.println(stringList.getClass() == intList.getClass());  // true! Both are just ArrayList at runtime

// if (stringList instanceof List<String>) { }  // COMPILE ERROR: illegal generic type check
if (stringList instanceof List<?>) { }  // legal -- only checks the raw type, ignoring the parameter
Real-world example
A serialization framework attempting to use reflection to determine a field's generic List<T>'s actual T at runtime discovers this information simply doesn't exist in the compiled bytecode at the object level (due to type erasure), requiring a different approach (like reading the field's declared generic type signature via reflection metadata, which IS preserved for fields/methods, just not for runtime object instances) to recover this information.
Likely follow-ups
  • Given type erasure removes runtime generic information from instances, how does reflection still manage to retrieve a field or method's generic signature information?
  • Why did Java choose erasure over reified generics (like C#'s approach, which does preserve runtime type information)?
Related topics