Java Type Erasure
What Type Erasure Is
Java's generics are checked by the compiler and then mostly removed from the compiled bytecode. This process is called type erasure:
- The compiler checks all generic code for type safety.
- It then replaces each type parameter with its bound —
Objectfor an unboundedT,NumberforT extends Number. - It inserts casts where values come out of generic code, and generates bridge methods where needed to keep polymorphism working.
At runtime, the JVM sees ordinary classes. List<String> and List<Integer> are both just List.
Why Java did it this way: generics arrived in Java 5, ten years after Java 1.0. Erasure meant that generic code compiled to the same bytecode format as before, ran on the existing JVM, and worked together with the huge amount of existing non-generic code and libraries (migration compatibility). The price is a set of restrictions that every Java developer runs into sooner or later — this lesson explains where they come from.
Seeing Erasure
Same class at runtime
import java.util.*;
public class Same {
public static void main(String[] args) {
List<String> names = new ArrayList<>();
List<Integer> ages = new ArrayList<>();
System.out.println(names.getClass() == ages.getClass());
System.out.println(names.getClass().getName());
System.out.println(names instanceof ArrayList<?>);
}
}
Output:
true
java.util.ArrayList
true
There is only one ArrayList class. The object doesn't remember whether it was created as a list of strings or of integers.
The compiled signatures
Given this class:
public class Box<T> {
private T value;
public void set(T value) { this.value = value; }
public T get() { return value; }
}
the javap tool (included with the JDK) shows the compiled method descriptors — the signatures the JVM actually uses:
$ javap -s Box
public class Box<T> {
public Box();
descriptor: ()V
public void set(T);
descriptor: (Ljava/lang/Object;)V
public T get();
descriptor: ()Ljava/lang/Object;
}
The source-level signatures (set(T), T get()) are kept as metadata, but the descriptors say Object: set takes an Object and get returns an Object. For a bounded type, the bound is used instead:
$ javap -s Bounded (class Bounded<T extends Number> { public T get() ... })
public T get();
descriptor: ()Ljava/lang/Number;
The inserted cast
For code that uses Box<String>:
public class UseBox {
public static void main(String[] args) {
Box<String> b = new Box<>();
b.set("Java");
String s = b.get();
System.out.println(s.length());
}
}
javap -c UseBox shows the bytecode the compiler generated:
11: invokevirtual #12 // Method Box.set:(Ljava/lang/Object;)V
14: aload_1
15: invokevirtual #16 // Method Box.get:()Ljava/lang/Object;
18: checkcast #20 // class java/lang/String
21: astore_2
get() returns an Object, and the compiler inserted a checkcast to String — exactly the cast you'd have written by hand before Java 5. Generics didn't remove the casts; they moved them into code the compiler writes for you, after first proving they're safe.
Consequences of Erasure
Most generic restrictions follow directly from "the type argument doesn't exist at runtime":
| Restriction | Reason |
|---|---|
No new T() or new T[n] | The JVM doesn't know which class T is |
No obj instanceof List<String> (only List<?>) | The object doesn't record its type argument |
No primitive type arguments (List<int>) | Erasure replaces T with Object (or a bound), and primitives aren't objects |
A class can't implement both Comparable<A> and Comparable<B> | After erasure, both are the same interface |
Static fields can't use T | There is one class (and one set of static fields) for all type arguments |
| Overloads can't differ only in type arguments | Their erased signatures are identical — shown next |
| Casts to generic types are unchecked | The JVM can check (List) o, not (List<String>) o |
Generic exception classes aren't allowed (class MyEx<T> extends Exception) | A catch clause needs a runtime type to match |
Overloads that erase to the same signature
import java.util.*;
public class Clash {
void print(List<String> names) { }
void print(List<Integer> numbers) { }
}
Clash.java:5: error: name clash: print(List<Integer>) and print(List<String>) have the same erasure
void print(List<Integer> numbers) { }
^
1 error
After erasure, both methods would be print(List), and the JVM couldn't tell them apart. Use different method names (printNames, printNumbers) or a single generic method instead.
Bridge Methods
Erasure creates a problem for polymorphism, which the compiler solves with bridge methods:
import java.lang.reflect.*;
import java.util.*;
public class Bridge {
record Course(String code, int fee) implements Comparable<Course> {
@Override public int compareTo(Course other) { return Integer.compare(fee, other.fee); }
}
public static void main(String[] args) {
for (Method m : Course.class.getDeclaredMethods()) {
if (m.getName().equals("compareTo")) {
System.out.println(m.getName() + "(" + m.getParameterTypes()[0].getSimpleName() + ") bridge=" + m.isBridge());
}
}
List<Course> list = new ArrayList<>(List.of(new Course("DJ", 5999), new Course("PY", 2999)));
Collections.sort(list);
System.out.println(list);
}
}
Output (the order in which reflection lists methods isn't guaranteed):
compareTo(Object) bridge=true
compareTo(Course) bridge=false
[Course[code=PY, fee=2999], Course[code=DJ, fee=5999]]
After erasure, the Comparable interface declares compareTo(Object). Course declares compareTo(Course), which, at the bytecode level, is a different method. Code like Collections.sort calls compareTo(Object) through the interface, so the compiler adds a hidden bridge method compareTo(Object) that casts its argument to Course and calls your compareTo(Course). Reflection shows both; isBridge() identifies the synthetic one.
You rarely need to think about bridge methods, but they explain two things you might see: extra methods in stack traces and reflection output, and a ClassCastException thrown from a line where you don't see any cast — the bridge's hidden cast failed because a wrong type got in through an unchecked operation.
Heap Pollution from Unchecked Casts
Because a cast to a generic type can't be checked at runtime, it's possible to trick the type system — with an @SuppressWarnings("unchecked") that hides the compiler's warning:
import java.util.*;
public class Pollute {
@SuppressWarnings("unchecked")
static <T> List<T> unsafeCast(Object o) {
return (List<T>) o;
}
public static void main(String[] args) {
List<Integer> ids = new ArrayList<>(List.of(101, 102));
List<String> names = unsafeCast(ids);
System.out.println("cast succeeded, size " + names.size());
names.add("Asha");
System.out.println("ids now: " + ids);
int first = ids.get(0);
System.out.println("first id: " + first);
int third = ids.get(2);
}
}
Output:
cast succeeded, size 2
ids now: [101, 102, Asha]
first id: 101
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
at Pollute.main(Pollute.java:17)
- The cast
(List<T>) oonly checks thatois aList— which it is — so it succeeds. The compiler would normally warn "unchecked cast"; the annotation silenced it. namesandidsnow refer to the same list. Adding"Asha"throughnamesputs aStringinto theList<Integer>.- Reading the first element works. Reading the third fails at line 17 — far from the real mistake — because the compiler-inserted
checkcasttoIntegerfinally meets the string.
This is heap pollution. The lesson: an unchecked warning means the compiler can no longer guarantee type safety. Suppress one only when you've proven the cast is correct, put the @SuppressWarnings on the smallest possible scope, and add a comment explaining why it's safe.
What Survives Erasure
Erasure removes type arguments from objects, but generic information written in declarations is kept in the class file as metadata and can be read through reflection:
import java.lang.reflect.*;
import java.util.*;
public class Kept {
static class Catalog {
private Map<String, List<Integer>> pricesByCourse = new HashMap<>();
public List<String> titles() { return List.of(); }
}
public static void main(String[] args) throws Exception {
Field f = Catalog.class.getDeclaredField("pricesByCourse");
System.out.println("field type: " + f.getType().getName());
System.out.println("generic field type: " + f.getGenericType());
Method m = Catalog.class.getMethod("titles");
System.out.println("generic return: " + m.getGenericReturnType());
List<Integer> local = new ArrayList<>();
System.out.println("object's class: " + local.getClass().getTypeName());
}
}
Output:
field type: java.util.Map
generic field type: java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
generic return: java.util.List<java.lang.String>
object's class: java.util.ArrayList
- The declared types of fields, method parameters and return types, and the type arguments in
extends/implementsclauses, are available throughgetGenericType(),getGenericReturnType(),getGenericSuperclass()and similar methods, which returnjava.lang.reflect.Typeobjects such asParameterizedType. - The object itself still doesn't know its type argument:
local.getClass()is justArrayList.
This is how frameworks like Jackson, Gson, Hibernate and Spring know that a field declared List<Address> should be filled with Address objects: they read the declaration, not the object.
Practical Example: Type Tokens for a Configuration Reader
A configuration reader should convert text values into whatever type the caller needs — int, boolean, Duration, even List<Integer>. Because of erasure, a generic method can't find out what T is from the call alone; the caller must pass the type as a runtime object, a type token. A Class<T> works for simple types. For generic types like List<Integer>, there is no List<Integer>.class, so the super type token trick captures the full type through an anonymous subclass's declaration — one of the declarations that survives erasure.
import java.lang.reflect.*;
import java.util.*;
import java.util.function.Function;
public class Config {
abstract static class TypeRef<T> {
final Type type;
protected TypeRef() {
Type superType = getClass().getGenericSuperclass();
this.type = ((ParameterizedType) superType).getActualTypeArguments()[0];
}
}
static final Map<Class<?>, Function<String, ?>> PARSERS = Map.of(
String.class, s -> s,
Integer.class, Integer::valueOf,
Boolean.class, Boolean::valueOf,
Double.class, Double::valueOf,
java.time.Duration.class, java.time.Duration::parse);
private final Map<String, String> raw;
Config(Map<String, String> raw) { this.raw = raw; }
<T> T get(String key, Class<T> type) {
String text = Objects.requireNonNull(raw.get(key), "missing key " + key);
Function<String, ?> parser = PARSERS.get(type);
if (parser == null) throw new IllegalArgumentException("no parser for " + type.getSimpleName());
return type.cast(parser.apply(text.strip()));
}
@SuppressWarnings("unchecked")
<T> T get(String key, TypeRef<T> ref) {
if (ref.type instanceof ParameterizedType p && p.getRawType() == List.class) {
Class<?> element = (Class<?>) p.getActualTypeArguments()[0];
List<Object> items = new ArrayList<>();
for (String part : raw.get(key).split(",")) {
items.add(PARSERS.get(element).apply(part.strip()));
}
return (T) List.copyOf(items);
}
throw new IllegalArgumentException("unsupported type " + ref.type);
}
public static void main(String[] args) {
Config cfg = new Config(Map.of(
"server.port", "8080", "feature.newCheckout", "true",
"session.timeout", "PT30M", "retry.delays", "100, 200, 400",
"admin.emails", "asha@gocourse.in, ravi@gocourse.in"));
int port = cfg.get("server.port", Integer.class);
boolean newCheckout = cfg.get("feature.newCheckout", Boolean.class);
java.time.Duration timeout = cfg.get("session.timeout", java.time.Duration.class);
System.out.println(port + 1 + " " + newCheckout + " " + timeout.toMinutes() + " min");
TypeRef<List<Integer>> listOfInts = new TypeRef<>() { };
System.out.println("captured type: " + listOfInts.type);
List<Integer> delays = cfg.get("retry.delays", listOfInts);
System.out.println("total delay: " + delays.stream().mapToInt(Integer::intValue).sum() + " ms");
List<String> admins = cfg.get("admin.emails", new TypeRef<List<String>>() { });
System.out.println("first admin: " + admins.get(0).toUpperCase());
}
}
Output:
8081 true 30 min
captured type: java.util.List<java.lang.Integer>
total delay: 700 ms
first admin: ASHA@GOCOURSE.IN
How it works:
Class<T>as a token.get("server.port", Integer.class)passes the class object, which exists at runtime. The method uses it to look up a parser, andtype.cast(...)performs a checked cast that returns aT— soint port = ...compiles without any unchecked warnings.- A parser table.
Map<Class<?>, Function<String, ?>>maps each supported type to a conversion function.Duration::parseunderstands ISO-8601 durations such asPT30M(30 minutes). - The super type token.
new TypeRef<List<Integer>>() { }creates an anonymous subclass whose declaration isextends TypeRef<List<Integer>>. That declaration is stored in the class file. The constructor callsgetClass().getGenericSuperclass(), gets aParameterizedType, and extracts the actual type argument:java.util.List<java.lang.Integer>— the full generic type, recovered despite erasure. The{ }is essential; without it, there's no subclass and no stored declaration (and the abstract class couldn't be instantiated anyway). - Using the captured type. The second
getchecks that the token is a parameterizedList, extracts the element class (IntegerorString), parses each comma-separated part with the matching parser, and returns an unmodifiable list. - One justified unchecked cast. The final
(T) List.copyOf(items)can't be checked by the JVM, but the method has built the list from exactly the element type the token describes, so the cast is correct. The@SuppressWarningsis limited to this method for that reason.
This is the technique behind Jackson's TypeReference (mapper.readValue(json, new TypeReference<List<Order>>() {})), Gson's TypeToken and Spring's ParameterizedTypeReference — whenever a library must produce a generic type such as List<Order> at runtime, you'll see an anonymous subclass with {} at the end.