Java Reference ยท Object-Oriented Concepts
Type erasure in Java generics
Reference for Java type erasure: how the compiler removes type arguments, bridge methods, heap pollution, reified type tokens and what you cannot do.
Java generics are implemented by erasure. The compiler checks your type arguments, inserts casts where needed, and then removes the arguments from the compiled code. At run time a List<String> and a List<Integer> are the same class, List. This kept generic code compatible with libraries written before Java 5, but it explains many rules that otherwise look arbitrary.
A type parameter is replaced by its leftmost bound, or by Object if it has none. class Box<T extends Number> erases to a field of type Number; <T> void f(T x) erases to f(Object).
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.
What erasure causes
| You cannot... | Why |
|---|---|
new T() or new T[n] |
T does not exist at run time. |
T.class |
No Class object for a type variable. Pass a Class<T> instead. |
x instanceof List<String> |
Only List<?> can be checked. |
Overload f(List<String>) and f(List<Integer>) |
Both erase to f(List); a name clash. |
Catch or throw a generic type (class MyEx<T> extends Exception) |
The runtime cannot tell the catch cases apart. |
| Use primitives as type arguments | Type arguments become Object or a bound, so only reference types fit. |
Static fields of type T |
One static field is shared by all parameterizations. |
Usage notes
- Bridge methods are synthetic methods the compiler adds so an override with a narrower type (
String next()) still matches the erased interface method (Object next()). They show up in reflection asisBridge(). - Heap pollution: unchecked casts or raw types can place a wrong object into a generic collection; the failure appears later as a
ClassCastExceptionfar from the cause. Treat unchecked warnings as bugs. - Metadata survives: field, method and superclass signatures keep generic information in class files. Libraries such as Jackson use the anonymous-subclass trick (
new TypeReference<List<Foo>>() { }) to recover it. - Varargs of generic type (
List<String>...) create warnings because the array is reified while its elements are not;@SafeVarargssuppresses it when you know the method is safe. - Performance: no extra objects exist for generics; boxing of primitives is the real cost.
- Not a flaw to hide: Project Valhalla (value classes) is exploring specialized generics, but erasure remains the model in Java 25.