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.
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<T>\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 -con 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 -vfor full constant pool and generic attribute debugging
Security Notes
- No runtime type enforcement:
List<String>andList<Integer>are both justListat 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
-
A type variable is not a class token:
List<String>.classis illegal. Pass aClass<String>token explicitly when code needs theStringclass at runtime. -
Varargs and heap pollution:
List<String>[]varargs can cause heap pollution because the array type is erased.@SafeVarargssuppresses the warning but does not fix the issue. -
Confusing errors when bounds are missing: If you call a method on
Tand it is not in the bound, the compile error references erasure — not the original type parameter. -
Generic enums with inheritance: Enum classes cannot extend other types, and generic enum declarations are not allowed because enums inherit
java.lang.Enumwhich is already parameterized.
Quick Recap
- Type erasure removes type arguments from ordinary runtime descriptors and checks
- Unbounded
<T>becomesObject; bounded<T extends X>becomesX - Class files may retain declared generic signatures for reflection and tools
- The compiler inserts casts and generates bridge methods where needed
List<String>andList<Integer>share the runtime classList.class; the JVM does not enforce their element types- Erasure is the reason you cannot
new T(), useT.class, orinstanceof List<String> - Erasure was chosen to maintain backward binary compatibility with Java 1.4 and earlier
Interview Questions
- >`. A `Class
Further Reading
- Generic Classes — defining classes with type parameters
- Generic Methods — writing flexible methods with type parameters
- Wildcards — unbounded and bounded wildcard type arguments
- Type Bounds — upper and lower bounds on type parameters
- Bridge Methods — compiler-generated methods from type erasure
- Oracle: Type Erasure — official documentation on how generics are erased at compile time
- OpenJDK: Type Erasure Source — source code showing generic type information retention
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.
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 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.