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 List and Map. Java met it with erasure. The compiler checks all type arguments, then produces bytecode in which:

  • every type parameter is replaced by its bound, Object if it has none, so List<String> and List<Integer> are both just List at run time;
  • casts are inserted where values come out, so String s = list.get(0) becomes a call returning Object followed by a 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 Signature attribute in the class file, so reflection can read Map<String, List<Integer>> from a field or a superclass. What is lost is the type argument of an object: an ArrayList does not know what it holds. Types whose full information is available at run time, such as String, int[], raw List or List<?>, are called reifiable.

What is erased and what is kept
InformationAt run timeHow to get it
Type argument of an object (new ArrayList<String>())ErasedNot possible; pass a Class<T> token
Type parameter inside a generic method or classErased to its boundNot possible
Generic type of a field, parameter or return typeKept as metadatagetGenericType(), getGenericReturnType()
Type arguments of a superclass or interfaceKept as metadatagetGenericSuperclass(): the super type token trick
Array component typesKept (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 Integer into a List<String> through a raw view.

Java
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:

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
  • ArrayList<String> and ArrayList<Integer> are the same runtime class: there is only one ArrayList.class.
  • For Box<T extends Comparable<T>>, the erased return type of get() is Comparable, the bound, while getGenericReturnType() still reports T from the metadata.
  • 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 List, the program added 42 to a List<String>. Nothing failed at that point, since the list only stores Objects. The failure came later, at strings.get(0), where the compiler's hidden cast to String threw ClassCastException, far from the line that caused it. This is heap pollution, and unchecked warnings exist to point at the lines that can cause it.

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's own messages.

Java
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:

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
  1. Two overloads that differ only in type arguments are a "name clash": after erasure both are handle(List), which a class file cannot hold twice. Give the methods different names.
  2. new T[10] is forbidden because the array must know its component type at run time and T is gone. Use a Class<T> token with Array.newInstance, or an Object[] inside the class, as ArrayList does.
  3. o instanceof List<String> on an Object is an error: the runtime check could only test List, so it cannot answer the question asked.
  4. new T() is impossible for the same reason; pass a Supplier<T> such as ArrayList::new instead.
  5. A cast to List<String> compiles, but with an "unchecked cast" warning: at run time it only checks List.
  6. Since Java 16 (JEP 394), instanceof List<String> is allowed when the static type already guarantees the type argument, as from Collection<String>; then only the reifiable part, List, needs checking.

Bridge methods

Comparator<T>.compare(T, T) erases to compare(Object, Object), but ByLength implements compare(String, String). In the JVM those are different methods, so the compiler adds a bridge.

Java
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:

Output
[String, String]  bridge=false
[Object, Object]  bridge=true
bridge cast failed for Integer arguments: ClassCastException
  • The class has two compare methods: the one written in source with String parameters, and a synthetic bridge with Object parameters that casts both arguments and calls the first. Method.isBridge() tells them apart; reflection code that lists methods often has to skip bridges to avoid seeing duplicates.
  • Calling the comparator through a raw type with two Integers went into the bridge, whose cast to String failed with ClassCastException. The bridge is where erased code meets the real types.
  • Bridges also appear for covariant return types, such as a clone() that returns the subclass type; they are visible with javap -p, as the bytecode 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.

Java
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:

Output
value instanceof List<?>: true
runtime class: java.util.ArrayList
toArray made: String[]
pair made Object[], cast to String[] failed: ClassCastException
  • instanceof List<?> works because the wildcard asks only what can be checked. The object's class is just ArrayList, never "ArrayList of String".
  • Called with two strings, the varargs method received a String[]: the caller knew T = String and created the array. Called from pair, where T is itself erased, the compiler had to create an Object[], and the caller's implicit cast to String[] failed.
  • @SafeVarargs is a promise that the method neither stores into nor exposes its varargs array. Returning the array breaks that promise, and javac warns about it; the warning is suppressed here only to demonstrate the failure.

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> token to create an array and filter a mixed list, then the super type token trick to capture a full nested type.

Java
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:

Output
created String[], length 3
strings only: [two, four]
captured full type: java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
  • Array.newInstance(String.class, 3) created a real String[], and type.isInstance with type.cast filtered the list without unchecked casts, keeping "two" and "four". The JDK uses the same idea in EnumSet.noneOf(Class) and Collections.checkedList.
  • A Class token cannot express Map<String, List<Integer>>. The anonymous subclass new TypeRef<Map<String, List<Integer>>>() { } can: its superclass type, with arguments, is stored in the class file, and the constructor reads it back with getGenericSuperclass(). The empty braces are essential; without them there is no subclass and nothing to read.
  • This is how Jackson's TypeReference, Gson's TypeToken and Spring's ParameterizedTypeReference work. See Jackson 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 List, 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. javac -Xlint:rawtypes reports every use, and new code should never need one; List<?> expresses "a list of something" safely.
  • Type arguments must be reference types, because erased code stores everything as Object. List<int> does not compile, and List<Integer> boxes every element into its own object, about 16 bytes each plus a 4-byte reference, as measured on the memory management page. Primitive arrays, IntStream and the primitive functional interfaces exist to avoid that cost.
  • Static members belong to the erased class, so a static field cannot use the class's type parameter, and there is one static field shared by Box<String> and Box<Integer>.
  • A catch clause cannot name a type parameter, and a generic class cannot extend Throwable, because exception handlers are matched by runtime class.

Choosing a work-around

When you need the type at run time
NeedUse
Create an array of TClass<T> and Array.newInstance, or IntFunction<T[]> such as String[]::new
Create an instance of TA Supplier<T>
Check or cast to TClass<T>.isInstance and cast
A full generic type such as List<Order>A super type token: new TypeReference<List<Order>>() { }
Two methods for different element typesDifferent method names, not overloads
Protect a collection from wrong elementsCollections.checkedList(list, String.class)
Unchecked warningsFix them, or suppress them on the smallest scope with a comment explaining why the cast is safe

See generics for the language rules, reflection for reading generic signatures, and varargs for the varargs side of heap pollution.