Skip to content
javahacks.dev
Java Core

Java Type Erasure and What It Breaks at Runtime Explained

See what generic type erasure removes at runtime, why new T and instanceof List of String fail, and the type token pattern that works around it.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the OpenJDK, Spring, Apache Maven and JUnit5 logos.

Java generics look like C++ templates or C# generics and are not. Generic types are checked by the compiler and then thrown away, a design decision from Java 5 that preserved compatibility with all the code written before generics existed. The price is a handful of restrictions that surprise everyone once: you cannot write new T(), you cannot ask whether an object is a List<String> and a generic method cannot tell, at run time, what its type argument was. This post shows exactly what erasure does by inspecting the bytecode, demonstrates each restriction with the compiler's own error message and then covers the three patterns that work around it. If the generics syntax itself is unfamiliar, start with Java generics, type parameters and wildcards.

What erasure does

The compiler does three things when it processes generic code. It checks that your usage is type correct. It replaces each type parameter with its bound, or Object if it has none. And it inserts casts wherever a value of a generic type is read. So this source:

src/main/java/dev/javahacks/generics/Box.javajava
package dev.javahacks.generics;

public class Box<T> {
    private T value;

    public void set(T value) { this.value = value; }
    public T get() { return value; }
}

compiles to the same bytecode as if you had written the field as Object value, with set(Object) and Object get(). A call site such as String s = box.get(); gets a cast added by the compiler. You can see this with javap, which prints the compiled signatures:

Shell
javap -p -cp target/classes dev.javahacks.generics.Box
Text
public class dev.javahacks.generics.Box<T> {
  private java.lang.Object value;
  public dev.javahacks.generics.Box();
  public void set(java.lang.Object);
  public java.lang.Object get();
}

Notice the Box<T> on the first line: the type parameter is recorded as metadata, but the members use Object. That metadata is why reflection can later tell you a field was declared as List<String>, as shown below. The values at run time, though, carry no type argument, and this is easy to prove:

java
List<String> strings = new ArrayList<>();
List<Integer> numbers = new ArrayList<>();
System.out.println(strings.getClass() == numbers.getClass());   // true
System.out.println(strings.getClass());                          // class java.util.ArrayList

Both lists are the same class. The "of String" and "of Integer" existed only in your source file.

What it breaks, one by one

Each of the following fails with a compile error because the compiler knows the information would be missing at run time.

You cannot instantiate a type parameter.

java
public class Factory<T> {
    public T create() {
        return new T();     // error: unexpected type; required: class; found: type parameter T
    }
}

There is no T at run time, so there is nothing to construct. The same applies to T.class.

**You cannot use instanceof with a parameterized type.**

java
Object o = new ArrayList<String>();
if (o instanceof List<String>) { }   // error: Object cannot be safely cast to List<String>
if (o instanceof List<?>) { }        // fine: the unbounded wildcard needs no runtime type

The JVM can check "is it a list", but it cannot check "of strings", because elements are not tagged.

You cannot create arrays of generic types.

java
List<String>[] groups = new List<String>[10];    // error: generic array creation

Arrays are reified, which means they remember their element type and check each store, while generics do not. Mixing the two would allow an unsafe store that the array could not detect. Use List<List<String>> or a list of lists instead.

Two overloads can collide after erasure.

java
void send(List<String> messages) { }
void send(List<Integer> ids) { }     // error: name clash: send(List<Integer>) and send(List<String>) have the same erasure

Both erase to send(List), so the JVM sees one method signature twice.

Primitive type arguments are not allowed, so List<int> does not compile; you need List<Integer> and the boxing that comes with it, a cost discussed in autoboxing and primitive versus wrapper types.

Heap pollution: the runtime consequence

Because the type argument is not checked at run time, you can sneak the wrong object into a generic collection through a raw type, and nothing fails until much later:

java
List<String> names = new ArrayList<>();
List raw = names;                 // unchecked warning
raw.add(42);                      // compiles, runs: no run time check on the element
String first = names.get(0);      // ClassCastException here, far from the cause
Text
Exception in thread "main" java.lang.ClassCastException: class java.lang.Integer cannot be cast to class java.lang.String
    at Demo.main(Demo.java:7)

The exception appears at the line that reads the value, where the compiler inserted its cast, not at the line that put the integer in. This is called heap pollution, and the compiler's unchecked warnings exist to flag its sources. Fixing ClassCastException from heap pollution shows how to trace one.

Bridge methods

Erasure interacts with overriding in a way that generates extra methods. A class that implements a generic interface:

java
public class NameComparator implements Comparator<String> {
    @Override
    public int compare(String a, String b) {
        return a.compareToIgnoreCase(b);
    }
}

After erasure the interface method is compare(Object, Object), which this class does not declare. To keep polymorphism working, the compiler adds a synthetic bridge method that casts and delegates:

Text
$ javap -p NameComparator
public class NameComparator implements java.util.Comparator<java.lang.String> {
  public int compare(java.lang.String, java.lang.String);
  public int compare(java.lang.Object, java.lang.Object);   // bridge, generated by the compiler
}

You rarely see bridge methods, but they appear in stack traces and in reflection results as isBridge() == true, and they explain why a ClassCastException can be thrown from a method with an unexpected name. They also relate to covariant return types, covered in covariant return types and bridge methods.

What survives: generic signatures in metadata

Erasure removes type arguments from values, but the compiler still writes the declared generic types into the class file's Signature attribute for fields, method parameters, return types and superclasses. Reflection can read them:

java
public class Inventory {
    private final Map<String, List<Integer>> stock = new HashMap<>();
}

Field f = Inventory.class.getDeclaredField("stock");
Type t = f.getGenericType();
System.out.println(t);     // java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>

if (t instanceof ParameterizedType p) {
    System.out.println(Arrays.toString(p.getActualTypeArguments()));
}
Text
java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
[class java.lang.String, java.util.List<java.lang.Integer>]

This is the loophole that makes many frameworks work. The declaration is metadata, so it can be read; a local variable or a particular instance has no such metadata. The distinction is the key to the next section.

Workaround 1: pass a Class token

If code needs to create instances, check types or cast safely, ask the caller for a Class<T>:

src/main/java/dev/javahacks/generics/Registry.javajava
public class Registry<T> {
    private final Class<T> type;
    private final List<T> items = new ArrayList<>();

    public Registry(Class<T> type) {
        this.type = type;
    }

    public void register(Object candidate) {
        items.add(type.cast(candidate));              // checked cast, fails with a clear message
    }

    public T createDefault() throws ReflectiveOperationException {
        return type.getDeclaredConstructor().newInstance();   // new T(), done by reflection
    }
}

var registry = new Registry<>(Order.class);

Class<T> carries exactly the information erasure removed. type.cast throws ClassCastException: Cannot cast java.lang.String to dev.javahacks.Order at the point of the mistake instead of later. The cost is an extra constructor argument and the limit that Class cannot express a parameterized type: there is no Class<List<String>>, only List.class.

Workaround 2: a Supplier

For creating instances, a factory is cleaner than reflection and works with constructors that need arguments:

java
public class Pool<T> {
    private final Supplier<T> factory;

    public Pool(Supplier<T> factory) { this.factory = factory; }

    public T acquire() { return factory.get(); }
}

var pool = new Pool<>(StringBuilder::new);

StringBuilder::new is a constructor reference, resolved by the compiler, so no reflection and no runtime failure when a constructor is missing. This is the idiom the JDK itself uses, for example in Optional.orElseGet and ThreadLocal.withInitial.

Workaround 3: the super type token

When you need the full parameterized type at run time, such as telling a JSON library to produce a List<Order>, a Class is not enough. The trick is to capture the type in a subclass declaration, where it is stored as metadata:

src/main/java/dev/javahacks/generics/TypeToken.javajava
public abstract class TypeToken<T> {
    private final Type type;

    protected TypeToken() {
        Type superclass = getClass().getGenericSuperclass();
        this.type = ((ParameterizedType) superclass).getActualTypeArguments()[0];
    }

    public Type type() { return type; }
}

Type listOfOrders = new TypeToken<List<Order>>() {}.type();
System.out.println(listOfOrders);     // java.util.List<dev.javahacks.Order>

The anonymous subclass new TypeToken<List<Order>>() {} has List<Order> written in its extends clause, and that is class metadata, not an erased value. The idea is named after Neal Gafter's *super type tokens* and is the same mechanism behind Jackson's TypeReference, Spring's ParameterizedTypeReference and Guava's TypeToken:

java
List<Order> orders = mapper.readValue(json, new TypeReference<List<Order>>() {});
List<Order> viaSpring = restClient.get().uri("/orders").retrieve()
        .body(new ParameterizedTypeReference<List<Order>>() {});

Without the anonymous subclass, mapper.readValue(json, List.class) returns a list of LinkedHashMap, because Jackson knows only that it should build a List and has no element type. That is a common bug whose real cause is erasure.

When this does not matter

For the everyday use of generics, collections and typed methods, erasure is invisible and the compile time checking is the benefit you wanted. It matters when you write reusable infrastructure, a framework, a mapper or a registry, or when you debug a mystery ClassCastException. Project Valhalla is working on specialised generics for value types that would reduce boxing, but erasure for reference types is part of the language and is staying. The references are the Java Tutorials on type erasure and JLS section 4.6 on type erasure.

Taggedexplainer
Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.