Type Erasure in Java Generics

Learn what Java type erasure changes in bytecode, what Signature attributes preserve for reflection, and why bridge methods keep generic overrides working.

published: reading time: 22 min read author: Geek Workbench updated: November 20, 2026
Quick Summary

Learn what Java type erasure changes in bytecode, what Signature attributes preserve for reflection, and why bridge methods keep generic overrides working.

The compiler checks Java’s generic type arguments, then uses erased types in ordinary JVM descriptors. An unbounded type variable becomes Object; a bounded one becomes its leftmost bound. A class file may also keep the declared generic types in a Signature attribute. Reflection and tools can read it, though the JVM does not use it for linkage or runtime type checks. This let Java add generic checks while keeping ordinary descriptors compatible with raw-type APIs. See JLS §4.6 and JVMS §4.7.9.

Introduction

Type erasure means type arguments such as <String> are not part of ordinary JVM descriptors or runtime type checks. A parameterized type like List<String> uses the same runtime class as raw List; a declared generic signature may still be kept in the class file for reflection and tools. A type variable does not provide a runtime class token, so Java does not allow T.class, new T(), a runtime check against List<String>, or direct creation of new T[].

Understanding erasure explains why those operations fail, why the compiler inserts casts, and why bridge methods appear in bytecode. It also lets generic code work with older APIs: List<String> and raw List have the same runtime class, though their source declarations differ.

The practical distinction is between a value’s runtime class and a declaration’s generic signature. The former is erased; the latter may remain inspectable through reflection. Neither makes the JVM enforce, for example, that a List<String> contains only strings. This post covers both sides, along with bridge methods and common erasure pitfalls.

What Gets Erased

Generic Declaration Erasure
<T> Object
<T extends Number> Number
<T extends Comparable<T>> Comparable (the bound, after its own erasure)
<K, V> (multiple) Each erased independently per its own bound
List<String> List (raw type)
List<? extends Number> List (descriptor; wildcard may remain in Signature)

The erased descriptors resemble pre-generics code that used Object and casts. A class file may also retain generic declaration metadata, and the compiler may add bridge methods to preserve overriding after erasure.

Code Example: Before and After Erasure

// SOURCE CODE
public class Container<T> {
    private T value;
    public T get() { return value; }
    public void set(T value) { this.value = value; }
}
// SIMPLIFIED ERASED VIEW (not a complete class-file listing)
public class Container {
    private Object value;  // T replaced with Object
    public Object get() { return value; }
    public void set(Object value) { this.value = value; }
}

The same happens at call sites:

// SOURCE
Container<String> box = new Container<>();
box.set("Hello");
// COMPILED
Container box = new Container();
box.set("Hello"); // "Hello" is already an Object — no cast needed
// retrieval: String s = box.get();
// compiler inserts: String s = (String) box.get();
// Erasure + cast insertion = what the compiler emits

Mermaid Diagram: Erasure Process — Compile Time


flowchart TD

    A["public class Box&lt;T&gt;\n{\n  T value;\n  T get() { return value; }\n}"] --> B["Type Checking"]

    B --> C["Erasure"]

    C --> D["public class Box\n{\n  Object value;\n  Object get() { return value; }\n}"]

    D --> E["Insert needed casts and bridges"]

    E --> F["Class file: erased descriptors + Signature metadata"]

Runtime Behavior

At runtime, new Box<String>() and new Box<Integer>() both create instances whose class is Box.class. The JVM uses erased descriptors for fields and methods, so it does not distinguish those instances by type argument or enforce the element type of a collection. The class file can still retain declarations in a Signature attribute, which reflection and tools can inspect. A field declared List<String> names has the descriptor Ljava/util/List; and may also have a signature Ljava/util/List<Ljava/lang/String;>;.

This matters for runtime checks. List<String> is not reifiable, so Java rejects a check such as Object value; value instanceof List<String>. List<String>.class is also illegal. Use List.class or value instanceof List<?> to check that a value is a list, then validate its elements if needed. Passing String.class gives a method an explicit class token; it does not recover an erased T by itself.

Reflection has two views of a declaration. For a Box<T> field declared as T value, Field.getType() returns the erased class (Object), while Field.getGenericType() can return the TypeVariable T from the class-file signature. For List<String> names, getType() returns List.class, while getGenericType() can return a ParameterizedType describing List<String>. Likewise, Method.getParameterTypes() reports erased Class objects, while getGenericParameterTypes() can report the declared generic types. These APIs expose metadata; they do not make the JVM enforce collection element types. Libraries such as Gson’s TypeToken can capture a parameterized type for their own runtime use. See Field.getGenericType().

Reflection can also inspect generic relationships declared through inheritance. For example, class StringBox extends Box<String> may expose Box<String> as its generic superclass because that declaration can be recorded in Signature. Reflection cannot infer the element types of arbitrary values just from their runtime classes.


flowchart TD

    G["Loading Box.class"]

    G --> H["Raw Box class and erased descriptors"]

    H --> I["Signature attribute may preserve declarations"]

    I --> J["Reflection and tools can inspect the signature"]

Bridge Methods

Erasure can change a method’s descriptor enough to break an override unless the compiler adds a bridge. This interface and implementation are a small example:

interface Mapper<T> {
    T map(T value);
}

final class StringMapper implements Mapper<String> {
    @Override
    public String map(String value) {
        return value.trim();
    }
}

Mapper<T>.map(T) erases to map(Object): Object. StringMapper.map(String) has a more specific descriptor, so javac emits a synthetic bridge with the erased descriptor. It casts the argument, then delegates to the typed method. A shortened javap -v StringMapper excerpt looks like this:

public java.lang.String map(java.lang.String);
  descriptor: (Ljava/lang/String;)Ljava/lang/String;
  flags: (0x0001) ACC_PUBLIC

public java.lang.Object map(java.lang.Object);
  descriptor: (Ljava/lang/Object;)Ljava/lang/Object;
  flags: (0x1041) ACC_PUBLIC, ACC_BRIDGE, ACC_SYNTHETIC
  Code:
    stack=2, locals=2, args_size=2
       0: aload_0
       1: aload_1
       2: checkcast     #8   // class java/lang/String
       5: invokevirtual #13  // Method map:(Ljava/lang/String;)Ljava/lang/String;
       8: areturn

The bridge is an actual method in the class file, separate from the generic Signature metadata. Reflection can identify one with Method.isBridge().

Code Example: Bounded Type Erasure

// SOURCE
public class NumericBox<T extends Number> {
    private T value;
    public double compute() {
        return value.doubleValue(); // calling Number's method
    }
}
// ERASED
public class NumericBox {
    private Number value;  // T replaced with leftmost bound: Number
    public double compute() {
        return value.doubleValue(); // still valid — Number has doubleValue()
    }
}

The erased field descriptor uses Number, which supplies the method called by compute().

Failure Scenarios

1. Cannot Instantiate T

The restriction against new T() follows from the fact that a type variable does not identify a constructor or runtime class. The compiler replaces T with its erasure in descriptors, but it can still preserve a declaration such as T in a class-file signature. That signature does not tell the JVM which concrete class a caller supplied for a particular invocation, so the compiler cannot generate a safe new T() operation.

public <T> void createInstance(Class<T> clazz) {
    // T t = new T(); // compile error: cannot do new T
    // Erasure makes T = Object at runtime, so new Object() would be wrong type
    T instance = clazz.getDeclaredConstructor().newInstance(); // workaround
}

new T() fails for a simple reason: a method cannot recover the caller’s type argument as a constructor target. An unbounded T has the descriptor Object, but constructing an Object would not create whatever subtype the caller expected. A Class<T> parameter is one way to pass the needed runtime class explicitly.

The standard workaround is passing a Class<T> token. The caller knows the actual type at the call site and passes MyClass.class. The method then uses clazz.getDeclaredConstructor().newInstance() to instantiate via reflection. This is how Spring, Hibernate, and most dependency injection containers build objects without knowing the concrete type at compile time. The tradeoff is that the wrong token produces a runtime exception instead of a compile-time error — you lose the safety net generics normally provide.

The deeper issue is that constructing T would require the method to know the caller’s chosen class. Java avoids carrying each type argument in ordinary runtime descriptors, which helps preserve compatibility with raw-type APIs. Languages with reified generic systems can support constrained generic construction because they retain the type argument at runtime.

The token gives reflection a concrete class to instantiate, but construction can still fail: the class needs an accessible no-argument constructor, and reflective construction can throw checked exceptions. Keep the Class<T> parameter typed so the compiler can check the relationship between the token and the method’s declared type.

2. Cannot Create Generic Arrays Directly

Arrays in Java carry their component class at runtime, and the JVM checks stores against it. Generic code cannot create new T[10] because it has no component class for T. Treating it as new Object[10] would not produce a String[] when a caller chose String as T; the declaration signature does not supply a per-call component class.

public <T> T[] makeArray(Class<T> componentType) {
    // T[] arr = new T[10]; // compile error
    // Pass the component class so the array has the right runtime type.
    @SuppressWarnings("unchecked")
    T[] arr = (T[]) Array.newInstance(componentType, 10);
    return arr;
}

Generic array creation runs into the same erasure problem: new T[10] is rejected because the required array component class is not available. The resulting array would need to be compatible with the caller’s T[], and an Object[] is not interchangeable with a String[].

Array.newInstance() uses the supplied component class to create the actual array type. The cast to T[] is unchecked because Java cannot prove the relationship between the token and the type variable inside the generic method. Raw types and generic varargs can still cause heap pollution; @SafeVarargs only suppresses a warning when the method meets the annotation’s safety requirements.

Java arrays are covariant: String[] is an Object[], and the array’s runtime component class still checks each store. Passing the right Class<T> to Array.newInstance() preserves that check. The generic signature alone cannot provide the component class, and an unchecked cast can still lie about the relationship between the class token and T.

3. Collision After Erasure

Method overloading in Java requires distinct method signatures — the JVM uses the full parameter type signature to resolve which method to invoke at a call site. When two methods have the same name but different parameter types at the source level, the JVM distinguishes them by those parameter types. But type erasure removes type arguments, potentially causing two source-level distinct methods to collapse into the same JVM signature.

// Two methods with the same erasure — compile error
class Colliding<T> {
    void set(T value) { }
    void set(Object value) { } // both erase to set(Object)
}

Method signature collision is a direct consequence of erasure. Two source declarations that differ only by type arguments can have the same erased descriptor. The compiler rejects the clash before producing bytecode.

The collision problem shows up when overloads differ only by type arguments. For example, void process(List<String> values) and void process(List<Integer> values) both erase to void process(List), so Java rejects them. Methods whose parameters erase to different types, such as Number and CharSequence, can coexist.

The compiler reports a name clash when two declarations have the same erased signature. Rename one method or change its parameter types so the descriptors differ.

4. Cannot Call Class methods on T at Runtime

public <T> void example(T param) {
    // Class<?> c = param.getClass(); // works — getClass() is on Object
    // But Class<T> methods that need T at runtime are unsafe
    // T.class cannot be used: Class<T> does not give you .class at runtime
}

param.getClass() works because every object has that method. It returns a Class<?> for the argument’s actual runtime class. But a method cannot derive the caller’s generic argument T from the type variable alone. A Class<T> parameter works because the caller passes a Class object explicitly.

The practical impact shows up when you try to use T.class as a class literal. T.class is a syntax error because T does not exist at runtime. Class<T> as a parameter type only carries the type information if the caller passes it explicitly. If you call save(String.class), the Class<String> token enters the method and you can use it for newInstance() calls or cast(). But inside the generic method itself, there is no way to derive a Class<T> from T alone. This is why many generic frameworks require you to pass the class token as an explicit parameter rather than trying to extract it from the type parameter.

Trade-Off Table

Concern Impact of Erasure Mitigation
instanceof with type arguments Type arguments are not runtime checks Check raw class, then validate elements
new T() Not possible Use Class<T>.newInstance() or Array.newInstance()
T.class Not valid syntax Pass Class<T> as parameter
Array creation No direct new T[] Use Array.newInstance() with unchecked cast
Bridge methods Compiler adds to preserve overrides Be aware when debugging bytecode
Binary compatibility Pre-generics code works with generics code No breaking changes to existing JARs

Observability Checklist

  • Use javap -c on compiled classes to see actual erased signatures and bridge methods
  • Check for “unchecked” warnings in compilation output — these signal erasure-related unsafe operations
  • Verify framework serialization does not rely on generic type parameters (most handle erasure via TypeToken / custom serializers)
  • Test with pre-generics code paths if maintaining binary compatibility with older JARs
  • Use javap -v for full constant pool and generic attribute debugging

Security Notes

  • No runtime type enforcement: List<String> and List<Integer> are both just List at runtime. Malicious code that bypasses generics can inject the wrong type. Validate at boundaries.
  • Unsafe casts: Erasure means the compiler inserts casts. If you use raw types or @SuppressWarnings("unchecked"), you bypass these safety nets. Audit for raw type usage in security-critical paths.
  • Reflection exposure: Field.getGenericType() can read declared generic metadata, while the field descriptor remains erased. The JVM does not validate stored values against that signature. Validate untrusted data at the boundary.

Pitfalls

  1. A type variable is not a class token: List<String>.class is illegal. Pass a Class<String> token explicitly when code needs the String class at runtime.

  2. Varargs and heap pollution: List<String>[] varargs can cause heap pollution because the array type is erased. @SafeVarargs suppresses the warning but does not fix the issue.

  3. Confusing errors when bounds are missing: If you call a method on T and it is not in the bound, the compile error references erasure — not the original type parameter.

  4. Generic enums with inheritance: Enum classes cannot extend other types, and generic enum declarations are not allowed because enums inherit java.lang.Enum which is already parameterized.

Quick Recap

  • Type erasure removes type arguments from ordinary runtime descriptors and checks
  • Unbounded <T> becomes Object; bounded <T extends X> becomes X
  • Class files may retain declared generic signatures for reflection and tools
  • The compiler inserts casts and generates bridge methods where needed
  • List<String> and List<Integer> share the runtime class List.class; the JVM does not enforce their element types
  • Erasure is the reason you cannot new T(), use T.class, or instanceof List<String>
  • Erasure was chosen to maintain backward binary compatibility with Java 1.4 and earlier

Interview Questions

1. What is type erasure in Java generics?
Type erasure removes type arguments from ordinary JVM descriptors and runtime checks. An unbounded type variable uses `Object` as its erasure; a bounded one uses its leftmost bound. `List` and `List` share the runtime class `List.class`, while a class file may retain the declared generic signature for reflection and tools.

2. Why did Java choose erasure over reified generics?
Erasure let Java add compile-time generic checks while keeping ordinary method and field descriptors compatible with raw-type code. The class file can also store generic declarations in a `Signature` attribute, which tools and reflection can inspect. The JVM does not use that signature to enforce type arguments during calls or collection operations.

3. Why cannot you instantiate a new T() in a generic class?
A type variable does not provide a constructor or runtime class token. The standard workaround is to pass a `Class` token, then use `clazz.getDeclaredConstructor().newInstance()`. The class-file signature records the declaration, but it does not tell a method which concrete class the caller supplied for that invocation.

4. How does the bound affect erasure of a type parameter?
The first bound is the erasure: `` becomes `Number`, not `Object`. With `>`, descriptors use `Number`; the generic signature can retain both bounds, and reflection can inspect the declaration.

5. What is the performance impact of type erasure at runtime?
Generic type arguments do not trigger per-element runtime checks or separate specialized classes. Erasure can still leave ordinary `checkcast` instructions and compiler-generated bridge methods in bytecode. Their cost depends on the code and what the JIT can optimize, so “zero runtime cost” is too broad.

6. What is the generic signature attribute in class files?
The `Signature` attribute records generic declarations in a class file. The JVM does not use it for linkage or runtime type enforcement, but tools such as `javap -v` and Java reflection can read it. For example, a field declared `Pair` still has a raw `Pair` descriptor; its `Signature` may preserve both type arguments.

7. Can two parameterized types have the same erasure?
Yes. `List` and `List` both erase to `List`; their type arguments are absent from ordinary runtime descriptors. If two overloads differ only by those arguments, such as `process(List)` and `process(List)`, Java rejects them because they have the same erased signature.

8. What is heap pollution and how does it relate to erasure?
Heap pollution occurs when a variable of a parameterized type refers to an object that does not match its declared type. `new List[5]` is illegal Java syntax because arrays cannot be created with a concrete parameterized component type. Pollution can still happen through raw types, unchecked casts, or generic varargs. `@SafeVarargs` suppresses a warning; use it only when the method implementation is safe.

9. How does reflection interact with generic type information after erasure?
Reflection exposes both views: `Field.getType()` returns the erased `Class` (for a `T` field, often `Object.class`), while `Field.getGenericType()` can return the declared `TypeVariable` or `ParameterizedType` recorded in the signature. That metadata describes the declaration; it does not prove an arbitrary field value or collection element has the declared type. A `Class` token must be passed explicitly when code needs a runtime class for `T`.

10. Can overloaded methods have the same erasure?
Two declarations cannot coexist as overloads if their erased signatures are the same. ` void process(T item)` erases to `process(Object)`, while ` void process(List list)` erases to `process(List)`, so those two descriptors differ. Overloads whose type parameters have distinct leftmost bounds, such as `Number` and `CharSequence`, also have distinct erasures.

11. Why cannot you use instanceof with parameterized types?
A runtime `instanceof` check cannot test a concrete type argument such as `String` in `List`. `obj instanceof List` can test that the object is a list, but element types need to be checked separately. A `Class` token can check a reifiable class such as `String`; it cannot represent `List` by itself.

12. What are the trade-offs of using type erasure in Java?
Erasure kept ordinary descriptors compatible with raw-type code, while allowing the compiler to check parameterized types. The class file can retain declaration metadata in `Signature` attributes, but runtime objects are not specialized by type argument and the JVM does not enforce generic element types.

13. Why does T super Number not compile in a type parameter declaration?
`super` is only valid in wildcard usage (`? super T`), not in a type parameter declaration. `` is a compile error. The `super` keyword in generics is used at the call site for lower-bounded wildcards to enable contravariant write flexibility. In a type parameter declaration, only `extends` is valid (upper bound). The lower bound concept exists only in existential type contexts with wildcards."

14. How does erasure work with nested generic types?
A descriptor for `Map>` uses the raw `Map` class. Its class-file `Signature` may preserve the nested `String` and `Integer` declarations, which reflection can inspect. Arrays add a separate constraint: Java cannot create an array whose component type is a concrete parameterized type such as `List`.

15. How does type erasure affect lambda expressions?
A lambda gets its parameter and return types from its target functional interface at compile time. The generated invocation uses the erased method descriptor, with casts or bridge methods where required by the surrounding code. A lambda object is not a separate runtime `Function` class just because that was its source-level target.

16. How does Java serialization handle generic types after erasure?
Standard Java serialization writes the runtime object graph, not the compile-time type argument for a collection. `List` and `List` do not become specialized list classes. Libraries can use an explicit type token or a subclass whose generic superclass signature captures a parameterized type, then apply that type information in their own serialization logic.

17. What are bridge methods and how do they relate to erasure?
A bridge is a synthetic method the compiler adds so an implementation with a specific generic type still matches the erased interface method. For example, implementing `Mapper.map(String)` also needs an `Object map(Object)` bridge that casts and delegates. You can identify bridge methods with `Method.isBridge()`.

18. Why does the compiler insert casts after type erasure?
The descriptor for `T get()` may return `Object`, while the source expression has a more specific type such as `String`. The compiler inserts a `checkcast` at the call site so the JVM checks the returned object before assigning it to a `String` variable. This is distinct from the compile-time checks that catch many type errors earlier.

19. Why is List.class illegal in Java?
`List.class` is illegal because class literals identify reifiable classes, and the runtime class is `List.class`. If code needs the full parameterized type, it can inspect a generic field or use a type-token pattern whose anonymous subclass declares a generic superclass such as `TypeToken>`. A `Class` token by itself represents one class, not a parameterized type.

20. What is the relationship between type inference and type erasure?
Type inference lets the compiler determine type arguments from a call site's context. Erasure then removes those arguments from ordinary descriptors and runtime checks. A class file may retain declared generic signatures for reflection and tools, but a particular invocation does not carry a runtime token for its inferred `T`.


Further Reading


Conclusion

Type erasure is how Java keeps generic type arguments out of ordinary JVM descriptors. An unbounded T erases to Object; T extends Number erases to Number. The compiler inserts casts where typed source code needs them and generates bridge methods when erased descriptors would otherwise break an override. List<String> and List<Integer> share the runtime class List.class.

That is why Java cannot construct new T(), use T.class, or check an arbitrary object for the type argument in List<String>. A type variable does not give code a runtime class token. You can pass a Class<T> explicitly when you need one.

Descriptors erase type arguments, but the class file may retain declared types in Signature attributes that reflection and tools can inspect. Field.getType() reports a field’s erased class, while Field.getGenericType() can report its declared type. The JVM does not use those signatures to enforce collection element types.

For a type variable with multiple bounds, <T extends Number & Comparable<T>> erases to the leftmost bound, Number. The Signature attribute can retain the full declaration, including Comparable<T>. Bridge methods handle a different issue: they preserve dispatch when a generic method’s erased descriptor differs from its implementation. See Erasure and Bridge Methods in Java for more examples.


Category

Related Posts

Abstract Classes in Java: Interfaces and Composition

Compare Java interfaces, abstract classes, and composition, then see when shared state, default methods, or sealed types change the design choice.

#java-abstract-classes #java #java-fundamentals

Arithmetic Operators in Java: Division, Overflow, Promotion

Compare Java arithmetic with runnable examples of division, negative remainders, overflow, type promotion, and BigDecimal for decimal money.

#java-arithmetic-operators #java #java-fundamentals

Java Array Basics: Length, Bounds, Copies, and Resizing

Learn Java arrays through runtime-sized allocation, bounds checks, aliasing, copying, and the fixed length that distinguishes them from ArrayList.

#java-array-basics #java #java-fundamentals