Type erasure: how generics work at run time
Java generics are checked by the compiler and then erased: the bytecode works with plain classes and the casts the compiler inserts. This page explains why Java chose erasure and what it keeps, then shows the compile errors it causes, the bridge methods it adds, how unchecked casts pollute the heap, why generic arrays break, and the type-token work-arounds libraries use when they need the type argument at run time.
Contents
What erasure means
Generics arrived in Java 5 (JSR 14) with one hard requirement: code compiled with generics had to run on the existing JVM and interoperate with millions of lines of pre-generics code that used raw ListMap
- every type parameter is replaced by its bound,
if it has none, soObject andList<String> are both justList<Integer> at run time;List - casts are inserted where values come out, so
becomes a call returningString s = list.get(0) followed by aObject ;checkcast String - bridge methods are generated where overriding with erased types would otherwise break.
Erasure is not total. The declarations keep their generic types in a SignatureMap<String, List<Integer>>ArrayListStringint[]ListList<?>
| Information | At run time | How to get it |
|---|---|---|
Type argument of an object (new ArrayList<String>() | Erased | Not possible; pass a Class<T> |
| Type parameter inside a generic method or class | Erased to its bound | Not possible |
| Generic type of a field, parameter or return type | Kept as metadata | getGenericType()getGenericReturnType() |
| Type arguments of a superclass or interface | Kept as metadata | getGenericSuperclass() |
| Array component types | Kept (arrays are reified) | getClass().getComponentType() |
The erasure examples were run on JDK 21. Project Valhalla plans to change part of this for value classes, but in released Java up to 25 the rules on this page hold.
What survives erasure
Two lists with different type arguments, a bounded generic class, and a field with a nested generic type show where the information goes. The last part puts an IntegerList<String>
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class ErasedAtRuntime {
static class Box<T extends Comparable<T>> {
T value;
T get() {
return value;
}
}
// Generic types written in declarations ARE kept, as metadata
static Map<String, List<Integer>> scores;
public static void main(String[] args) throws Exception {
List<String> a = new ArrayList<>();
List<Integer> b = new ArrayList<>();
System.out.println("same runtime class: " + (a.getClass() == b.getClass()));
// The type parameter is replaced by its bound in the bytecode
Method get = Box.class.getDeclaredMethod("get");
System.out.println("Box.get() erased return type: " + get.getReturnType().getSimpleName());
System.out.println("Box.get() generic return type: " + get.getGenericReturnType());
Field f = ErasedAtRuntime.class.getDeclaredField("scores");
ParameterizedType pt = (ParameterizedType) f.getGenericType();
System.out.println("declared field type kept: " + pt.getTypeName());
// Heap pollution: an unchecked cast lets the wrong type into a List<String>
List<String> strings = new ArrayList<>();
@SuppressWarnings({"unchecked", "rawtypes"})
List<Object> raw = (List) strings;
raw.add(42); // no error here...
System.out.println("list contents: " + strings);
try {
String s = strings.get(0); // ...the compiler-inserted cast fails here
System.out.println(s);
} catch (ClassCastException e) {
System.out.println("ClassCastException far from the real mistake");
}
}
}
Output:
same runtime class: true
Box.get() erased return type: Comparable
Box.get() generic return type: T
declared field type kept: java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
list contents: [42]
ClassCastException far from the real mistake
andArrayList<String> are the same runtime class: there is only oneArrayList<Integer> .ArrayList.class- For
, the erased return type ofBox<T extends Comparable<T>> isget() , the bound, whileComparable still reportsgetGenericReturnType() from the metadata.T - The declared type of the static field survived completely, nested arguments included. That is what frameworks such as Jackson and dependency injection containers rely on.
- Through a raw
, the program added 42 to aList . Nothing failed at that point, since the list only storesList<String> s. The failure came later, atObject , where the compiler's hidden cast tostrings.get(0) threwString , far from the line that caused it. This is heap pollution, and unchecked warnings exist to point at the lines that can cause it.ClassCastException
Compile errors that erasure causes
Several rules that surprise newcomers to generics follow directly from erasure. The program compiles six small sources with the compiler API and prints javac
import java.net.URI;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import javax.tools.Diagnostic;
import javax.tools.DiagnosticCollector;
import javax.tools.JavaCompiler;
import javax.tools.JavaFileObject;
import javax.tools.SimpleJavaFileObject;
import javax.tools.ToolProvider;
public class CompileErrors {
// Small sources that erasure makes illegal, or legal only with a warning
static final Map<String, String> CASES = new TreeMap<>(Map.of(
"1 overload by type argument", """
import java.util.List;
class C {
void handle(List<String> s) { }
void handle(List<Integer> i) { }
}""",
"2 generic array creation", """
class C<T> {
T[] make() { return new T[10]; }
}""",
"3 instanceof with type argument", """
import java.util.*;
class C {
boolean test(Object o) { return o instanceof List<String>; }
}""",
"4 new T()", """
class C<T> {
T make() { return new T(); }
}""",
"5 unchecked cast", """
import java.util.*;
class C {
List<String> cast(Object o) { return (List<String>) o; }
}""",
"6 instanceof that cannot fail (Java 16)", """
import java.util.*;
class C {
boolean test(Collection<String> c) { return c instanceof List<String>; }
}"""));
public static void main(String[] args) {
JavaCompiler javac = ToolProvider.getSystemJavaCompiler();
for (var e : CASES.entrySet()) {
DiagnosticCollector<JavaFileObject> diags = new DiagnosticCollector<>();
JavaFileObject src = new SimpleJavaFileObject(URI.create("string:///C.java"),
JavaFileObject.Kind.SOURCE) {
@Override
public CharSequence getCharContent(boolean ignoreEncodingErrors) {
return e.getValue();
}
};
List<String> options = List.of("-Xlint:unchecked", "-proc:none",
"-d", System.getProperty("java.io.tmpdir"));
boolean ok = javac.getTask(null, null, diags, options, null, List.of(src)).call();
System.out.println(e.getKey().substring(2) + ": " + (ok ? "compiles" : "error"));
for (Diagnostic<? extends JavaFileObject> d : diags.getDiagnostics()) {
String msg = d.getMessage(null).lines().findFirst().orElse("");
System.out.println(" " + d.getKind().toString().toLowerCase() + ": " + msg);
}
}
}
}
Output:
overload by type argument: error
error: name clash: handle(java.util.List<java.lang.Integer>) and handle(java.util.List<java.lang.String>) have the same erasure
generic array creation: error
error: generic array creation
instanceof with type argument: error
error: java.lang.Object cannot be safely cast to java.util.List<java.lang.String>
new T(): error
error: unexpected type
unchecked cast: compiles
mandatory_warning: unchecked cast
instanceof that cannot fail (Java 16): compiles
- Two overloads that differ only in type arguments are a "name clash": after erasure both are
, which a class file cannot hold twice. Give the methods different names.handle(List) is forbidden because the array must know its component type at run time andnew T[10] is gone. Use aT token withClass<T> , or anArray.newInstance inside the class, asObject[] does.ArrayList on ano instanceof List<String> is an error: the runtime check could only testObject , so it cannot answer the question asked.List is impossible for the same reason; pass anew T() such asSupplier<T> instead.ArrayList::new- A cast to
compiles, but with an "unchecked cast" warning: at run time it only checksList<String> .List - Since Java 16 (JEP 394),
is allowed when the static type already guarantees the type argument, as frominstanceof List<String> ; then only the reifiable part,Collection<String> , needs checking.List
Bridge methods
Comparator<T>.compare(T, T)compare(Object, Object)ByLengthcompare(String, String)
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Comparator;
public class BridgeMethods {
static class ByLength implements Comparator<String> {
@Override
public int compare(String a, String b) {
return Integer.compare(a.length(), b.length());
}
}
public static void main(String[] args) {
// Comparator<T>.compare erases to compare(Object, Object); the compiler adds a bridge
Arrays.stream(ByLength.class.getDeclaredMethods())
.filter(m -> m.getName().equals("compare"))
.sorted(Comparator.comparing(Method::isBridge))
.forEach(m -> System.out.println(Arrays.toString(m.getParameterTypes())
.replace("class java.lang.", "") + " bridge=" + m.isBridge()));
// Calling through the raw interface goes through the bridge, which casts
@SuppressWarnings("unchecked")
Comparator<Object> raw = (Comparator<Object>) (Comparator<?>) new ByLength();
try {
raw.compare(1, 2);
} catch (ClassCastException e) {
System.out.println("bridge cast failed for Integer arguments: ClassCastException");
}
}
}
Output:
[String, String] bridge=false
[Object, Object] bridge=true
bridge cast failed for Integer arguments: ClassCastException
- The class has two
methods: the one written in source withcompare parameters, and a synthetic bridge withString parameters that casts both arguments and calls the first.Object tells them apart; reflection code that lists methods often has to skip bridges to avoid seeing duplicates.Method.isBridge() - Calling the comparator through a raw type with two
s went into the bridge, whose cast toInteger failed withString . The bridge is where erased code meets the real types.ClassCastException - Bridges also appear for covariant return types, such as a
that returns the subclass type; they are visible withclone() , as thejavap -pbytecode page shows.
Arrays, varargs and reifiable types
Arrays know their component type at run time and check every store; generics do not. Mixing the two goes wrong in a way that compiles. A generic varargs helper is called once directly with strings and once from another generic method.
import java.util.ArrayList;
import java.util.List;
public class Reifiable {
// This annotation is a promise that the method is safe. Here the promise is false:
// returning the varargs array lets an Object[] escape to a caller expecting T[].
// javac sees through it and warns [varargs]; the warning is silenced only for this demo
@SafeVarargs
@SuppressWarnings("varargs")
static <T> T[] toArray(T... items) {
return items;
}
static <T> T[] pair(T a, T b) {
return toArray(a, b); // T is erased, so javac creates an Object[] here
}
public static void main(String[] args) {
Object value = new ArrayList<String>();
// List<?> is reifiable: the check needs only the class, which exists at run time
System.out.println("value instanceof List<?>: " + (value instanceof List<?>));
// The object itself records only ArrayList, never the String argument
System.out.println("runtime class: " + value.getClass().getName());
String[] direct = toArray("a", "b"); // caller knows T=String, so a String[] is made
System.out.println("toArray made: " + direct.getClass().getSimpleName());
try {
String[] viaPair = pair("a", "b");
System.out.println(viaPair.length);
} catch (ClassCastException e) {
System.out.println("pair made Object[], cast to String[] failed: ClassCastException");
}
}
}
Output:
value instanceof List<?>: true
runtime class: java.util.ArrayList
toArray made: String[]
pair made Object[], cast to String[] failed: ClassCastException
works because the wildcard asks only what can be checked. The object's class is justinstanceof List<?> , never "ArrayList of String".ArrayList- Called with two strings, the varargs method received a
: the caller knewString[] and created the array. Called fromT = String , wherepair is itself erased, the compiler had to create anT , and the caller's implicit cast toObject[] failed.String[] is a promise that the method neither stores into nor exposes its varargs array. Returning the array breaks that promise, and@SafeVarargs warns about it; the warning is suppressed here only to demonstrate the failure.javac
Getting type arguments back: type tokens
When code needs the type at run time, it must be passed in. The program uses a Class<T>
import java.lang.reflect.Array;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
public class TypeTokens {
// Work-around 1: pass a Class<T> so code can create and check T at run time
static <T> T[] newArray(Class<T> type, int size) {
@SuppressWarnings("unchecked")
T[] array = (T[]) Array.newInstance(type, size);
return array;
}
static <T> List<T> onlyOfType(List<?> items, Class<T> type) {
List<T> out = new ArrayList<>();
for (Object o : items) {
if (type.isInstance(o)) {
out.add(type.cast(o));
}
}
return out;
}
// Work-around 2: the "super type token" (Jackson's TypeReference, Gson's TypeToken)
abstract static class TypeRef<T> {
final Type type;
TypeRef() {
ParameterizedType sup = (ParameterizedType) getClass().getGenericSuperclass();
type = sup.getActualTypeArguments()[0];
}
}
public static void main(String[] args) {
String[] names = newArray(String.class, 3);
String kind = names.getClass().getSimpleName();
System.out.println("created " + kind + ", length " + names.length);
List<Object> mixed = List.of(1, "two", 3.0, "four");
System.out.println("strings only: " + onlyOfType(mixed, String.class));
TypeRef<Map<String, List<Integer>>> ref = new TypeRef<>() {
};
System.out.println("captured full type: " + ref.type.getTypeName());
}
}
Output:
created String[], length 3
strings only: [two, four]
captured full type: java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
created a realArray.newInstance(String.class, 3) , andString[] withtype.isInstance filtered the list without unchecked casts, keeping "two" and "four". The JDK uses the same idea intype.cast andEnumSet.noneOf(Class) .Collections.checkedList- A
token cannot expressClass . The anonymous subclassMap<String, List<Integer>> can: its superclass type, with arguments, is stored in the class file, and the constructor reads it back withnew TypeRef<Map<String, List<Integer>>>() { } . The empty braces are essential; without them there is no subclass and nothing to read.getGenericSuperclass() - This is how Jackson's
, Gson'sTypeReference and Spring'sTypeToken work. SeeParameterizedTypeReferenceJackson ObjectMapper for it in use.
Raw types and primitive type arguments
Two more everyday consequences of erasure are worth knowing.
- A raw type, such as plain
, exists only for compatibility with pre-Java 5 code. Using one switches off generic checking for every call on that variable, which is how the heap pollution above slipped through.List reports every use, and new code should never need one;javac -Xlint:rawtypes expresses "a list of something" safely.List<?> - Type arguments must be reference types, because erased code stores everything as
.Object does not compile, andList<int> boxes every element into its own object, about 16 bytes each plus a 4-byte reference, as measured on theList<Integer>memory management page . Primitive arrays, and the primitive functional interfaces exist to avoid that cost.IntStream - Static members belong to the erased class, so a
field cannot use the class's type parameter, and there is one static field shared bystatic andBox<String> .Box<Integer> - A
clause cannot name a type parameter, and a generic class cannot extendcatch , because exception handlers are matched by runtime class.Throwable
Choosing a work-around
| Need | Use |
|---|---|
Create an array of T | Class<T>Array.newInstanceIntFunction<T[]>String[]::new |
Create an instance of T | A Supplier<T> |
Check or cast to T | Class<T>.isInstancecast |
A full generic type such as List<Order> | A super type token: new TypeReference<List<Order>>() { } |
| Two methods for different element types | Different method names, not overloads |
| Protect a collection from wrong elements | Collections.checkedList(list, String.class) |
| Unchecked warnings | Fix them, or suppress them on the smallest scope with a comment explaining why the cast is safe |
See