Java Type Erasure: Raw Types, Translation and Bridge Methods
Understand how Java generics really work: type erasure to raw types and first bounds, the casts the compiler inserts, how generic methods are erased, bridge methods for overriding and covariant returns, calling legacy raw-type code, and generic record patterns.
kvi5hnuCode Sprout team member11 min readOn this page
The Java virtual machine has no generic types. Every object belongs to an ordinary class, and there is only one Pair class, whether your code says Pair<String> or Pair<LocalDate>. An early prototype of Java generics could even compile generic programs into class files that ran on Java 1.0 virtual machines! The compiler achieves this by erasing type parameters. Knowing how erasure works explains many of the rules and restrictions of Java generics, and the strange extra methods you'll occasionally see in stack traces.
Type erasure
Every generic type has a corresponding raw type: the generic type's name with the type parameters removed. Type variables are erased and replaced by their bound, or by Object if they have no bound.
The raw type of Pair<T> looks like this:
public class Pair {
private Object first;
private Object second;
public Pair(Object first, Object second) {
this.first = first;
this.second = second;
}
public Object getFirst() { return first; }
public Object getSecond() { return second; }
public void setFirst(Object newValue) { first = newValue; }
public void setSecond(Object newValue) { second = newValue; }
}
T has no bound, so it becomes Object. The result is an ordinary class, just as you'd have written it before generics existed. Your program may contain Pair<String>, Pair<LocalDate> and many more, but erasure turns all of them into the raw Pair type.
Erasure uses the first bound
A bounded type variable is replaced by its first bound. Consider:
public class Interval<T extends Comparable<T> & Serializable> implements Serializable {
private T lower;
private T upper;
. . .
public Interval(T first, T second) {
if (first.compareTo(second) <= 0) { lower = first; upper = second; }
else { lower = second; upper = first; }
}
}
Its raw type is:
public class Interval implements Serializable {
private Comparable lower;
private Comparable upper;
. . .
public Interval(Comparable first, Comparable second) { . . . }
}
Translating generic expressions
When your code calls a generic method whose return type has been erased, the compiler inserts a cast. For example:
Pair<Employee> buddies = . . .;
Employee buddy = buddies.getFirst();
The erased getFirst returns Object, so the compiler translates the call into two virtual machine instructions:
- A call to the raw method
Pair.getFirst. - A cast of the returned
ObjecttoEmployee.
Casts are also inserted when you access a generic field. If first were public (legal, if poor style), then
Employee buddy = buddies.first;
would also compile to a field read plus a cast. These casts can never fail as long as all your code compiles without "unchecked" warnings. That is the guarantee generics provide.
Translating generic methods
Erasure applies to generic methods too. You might think of
public static <T extends Comparable<T>> T min(T[] a)
as a whole family of methods, but after erasure only one remains:
public static Comparable min(Comparable[] a)
The type parameter is gone, leaving only its bound, Comparable.
Bridge methods
Erasure causes a subtle problem with overriding. Consider:
class DateInterval extends Pair<LocalDate> {
public void setSecond(LocalDate second) {
if (second.compareTo(getFirst()) >= 0)
super.setSecond(second);
}
. . .
}
A date interval is a pair of dates, and we override setSecond so the second value can never be earlier than the first. After erasure, the class looks like this:
class DateInterval extends Pair { // after erasure
public void setSecond(LocalDate second) { . . . }
. . .
}
But DateInterval also inherits a different setSecond from the raw Pair:
public void setSecond(Object second)
Its parameter type is Object, not LocalDate, so technically it's a different method. Yet it shouldn't be. Consider:
var interval = new DateInterval(. . .);
Pair<LocalDate> pair = interval; // OK: assignment to superclass
pair.setSecond(aDate);
We expect the call to be polymorphic: pair refers to a DateInterval, so DateInterval.setSecond should run and enforce its rule. Erasure would break that. The variable's type Pair<LocalDate> has only one setSecond, which erases to setSecond(Object), and DateInterval doesn't override that one.
To preserve polymorphism, the compiler generates a bridge method in DateInterval:
public void setSecond(Object second) { setSecond((LocalDate) second); }

Follow the call pair.setSecond(aDate):
pairhas declared typePair<LocalDate>, whose onlysetSecondmethod issetSecond(Object). So the compiler emits a call to that method.- The virtual machine calls
setSecond(Object)on the actual object, aDateInterval. That is the synthesized bridge method. - The bridge casts the argument and calls
DateInterval.setSecond(LocalDate), exactly what we want.
Bridges that differ only in return type
It gets stranger. Suppose DateInterval also overrides getSecond:
class DateInterval extends Pair<LocalDate> {
public LocalDate getSecond() { return (LocalDate) super.getSecond(); }
. . .
}
After erasure, DateInterval has two getSecond methods:
LocalDate getSecond() // defined in DateInterval
Object getSecond() // bridge: overrides the method defined in Pair, calls the first one
You couldn't write that in Java: two methods with the same name and parameter types are illegal. But in the virtual machine, a method is identified by its name, parameter types and return type. So the compiler can generate methods that differ only in return type, and the VM handles them correctly.
The facts to remember
- The virtual machine has no generics, only ordinary classes and methods.
- All type parameters are replaced by their bounds (or
Object). - Bridge methods are synthesized to preserve polymorphism.
- Casts are inserted as needed to preserve type safety.
Calling legacy code
A major goal of Java's generics design was interoperability with code written before generics. Plenty of such code still exists, and it uses raw types.
The Swing toolkit is a classic example. JSlider lets you label its tick marks with the method
void setLabelTable(Dictionary table)
Dictionary maps integers to label components. Java 5 made Dictionary generic, but JSlider was never updated, so it still uses the raw type. When you fill the table, you can use the generic type:
Dictionary<Integer, Component> labelTable = new Hashtable<>();
labelTable.put(0, new JLabel(new ImageIcon("nine.gif")));
labelTable.put(20, new JLabel(new ImageIcon("ten.gif")));
. . .
Passing a parameterized type where a raw type is expected compiles without a warning:
slider.setLabelTable(labelTable); // OK
Still, think about what the legacy method might do. It could replace the keys with strings and break your Dictionary<Integer, Component>. In this case, JSlider only reads the table, so you're safe.
The opposite direction, receiving a raw type from legacy code and assigning it to a generic type, does produce a warning:
Dictionary<Integer, Component> labelTable = slider.getLabelTable(); // warning: unchecked conversion
That's acceptable after you've reviewed the situation and made sure the table really contains Integer keys and Component values. There's never an absolute guarantee, since someone could have installed a different Dictionary in the slider. But you're no worse off than before generics. In the worst case, a ClassCastException occurs later.
Once you've thought it through, make the warning disappear with an annotation, either on the local variable:
@SuppressWarnings("unchecked")
Dictionary<Integer, Component> labelTable = slider.getLabelTable(); // no warning
or on a whole method:
@SuppressWarnings("unchecked")
public void configureSlider() { . . . }
The method-level annotation turns off unchecked warnings for all code in the method, so prefer the narrowest scope possible. Add a comment explaining why the code is safe.
Generic record patterns
Records can be generic, and record patterns (Java 21) work with them too. Make Pair a record:
record Pair<T>(T first, T second) { }
Now you can deconstruct a pair in a pattern:
var p = new Pair<String>("Hello", "World");
if (p instanceof Pair(var a, var b)) System.out.println(a.length() + b.length());
The type argument of the pattern is inferred, here as Pair<String>, so a and b are String variables. You can also give it explicitly:
p instanceof Pair<String>(var a, var b)
p instanceof Pair<String>(String a, String b)
When the static type is Object, use a wildcard or let inference do the work. Because of erasure, a pattern can't check the type argument itself at run time, but it can check the components: o instanceof Pair<?>(String a, String b) matches only pairs whose two components are strings. Generic record patterns work in switch too, as later articles show.
A complete example
import java.io.Serializable;
import java.lang.reflect.*;
import java.time.*;
import java.util.*;
public class Solution {
public static void main(String[] args) throws Exception {
// 1. one class at run time, no matter the type arguments
var words = new Pair<String>("a", "b");
var dates = new Pair<LocalDate>(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 12, 31));
System.out.println("same class: " + (words.getClass() == dates.getClass()) + ", " + words.getClass().getName());
// 2. erased field and method types: T becomes Object, or the first bound
System.out.println("Pair.first: " + Pair.class.getDeclaredField("first").getType().getSimpleName());
System.out.println("Interval.lower: " + Interval.class.getDeclaredField("lower").getType().getSimpleName());
System.out.println("Pair.getFirst returns " + Pair.class.getMethod("getFirst").getReturnType().getSimpleName());
Method min = ArrayAlg.class.getMethod("min", Comparable[].class);
System.out.println("erased generic method: " + min.getReturnType().getSimpleName() + " min("
+ min.getParameterTypes()[0].getSimpleName() + ")");
System.out.println("but the generic signature survives for reflection: " + min.toGenericString());
// 3. bridge methods keep overriding polymorphic after erasure
var interval = new DateInterval(LocalDate.of(2024, 1, 1), LocalDate.of(2024, 6, 30));
Pair<LocalDate> pair = interval;
pair.setSecond(LocalDate.of(2023, 1, 1)); // goes through the bridge to DateInterval.setSecond
System.out.println("second after bad update: " + pair.getSecond());
pair.setSecond(LocalDate.of(2024, 9, 30));
System.out.println("second after good update: " + pair.getSecond());
Arrays.stream(DateInterval.class.getDeclaredMethods())
.map(m -> (m.isBridge() ? "bridge " : "declared ") + m.getReturnType().getSimpleName() + " "
+ m.getName() + Arrays.toString(Arrays.stream(m.getParameterTypes()).map(Class::getSimpleName).toArray()))
.sorted()
.forEach(System.out::println);
// covariant return types use bridges too
Arrays.stream(Employee.class.getDeclaredMethods())
.filter(m -> m.getName().equals("clone"))
.map(m -> (m.isBridge() ? "bridge " : "declared ") + m.getReturnType().getSimpleName() + " clone()")
.sorted()
.forEach(System.out::println);
// 4. legacy code with raw types: warnings you can review and suppress
@SuppressWarnings("unchecked") // reviewed: makeLabels only stores Integer keys and String values
Map<Integer, String> labels = LegacyLib.makeLabels();
System.out.println("labels from legacy code: " + labels);
LegacyLib.printAll(labels); // a parameterized type is accepted where a raw type is expected
// 5. generic record patterns (Java 21)
Object o = new Couple<>("Hello", "World");
if (o instanceof Couple<?>(String a, String b)) System.out.println(a.length() + b.length() + " letters");
var c = new Couple<>(3, 4);
if (c instanceof Couple(var x, var y)) System.out.println("x * y = " + x * y); // Couple<Integer> inferred
}
}
class Pair<T> {
private T first;
private T second;
public Pair(T first, T second) { this.first = first; this.second = second; }
public T getFirst() { return first; }
public T getSecond() { return second; }
public void setFirst(T newValue) { first = newValue; }
public void setSecond(T newValue) { second = newValue; }
}
class Interval<T extends Comparable<T> & Serializable> implements Serializable {
private static final long serialVersionUID = 1L;
private T lower;
private T upper;
public Interval(T first, T second) {
if (first.compareTo(second) <= 0) { lower = first; upper = second; }
else { lower = second; upper = first; }
}
@Override public String toString() { return "[" + lower + ", " + upper + "]"; }
}
class ArrayAlg {
public static <T extends Comparable<T>> T min(T[] a) {
T smallest = a[0];
for (T t : a) if (t.compareTo(smallest) < 0) smallest = t;
return smallest;
}
}
class DateInterval extends Pair<LocalDate> {
public DateInterval(LocalDate first, LocalDate second) { super(first, second); }
@Override
public void setSecond(LocalDate second) {
if (second.compareTo(getFirst()) >= 0) // never let the interval end before it starts
super.setSecond(second);
}
@Override
public LocalDate getSecond() { return super.getSecond(); }
}
class Employee implements Cloneable {
@Override
public Employee clone() throws CloneNotSupportedException { return (Employee) super.clone(); }
}
/** Pretend this class was written before Java 5. */
class LegacyLib {
@SuppressWarnings({ "rawtypes", "unchecked" })
static Map makeLabels() {
Map m = new TreeMap();
m.put(0, "zero");
m.put(10, "ten");
return m;
}
@SuppressWarnings("rawtypes")
static void printAll(Map m) {
for (Object key : m.keySet()) System.out.println(" " + key + " = " + m.get(key));
}
}
record Couple<T>(T first, T second) { }
same class: true, Pair
Pair.first: Object
Interval.lower: Comparable
Pair.getFirst returns Object
erased generic method: Comparable min(Comparable[])
but the generic signature survives for reflection: public static <T extends java.lang.Comparable<T>> T ArrayAlg.min(T[])
second after bad update: 2024-06-30
second after good update: 2024-09-30
bridge Object getSecond[]
bridge void setSecond[Object]
declared LocalDate getSecond[]
declared void setSecond[LocalDate]
bridge Object clone()
declared Employee clone()
labels from legacy code: {0=zero, 10=ten}
0 = zero
10 = ten
10 letters
x * y = 12
Notice the "bad update": through the Pair<LocalDate> variable, the attempt to set an earlier end date still reached DateInterval's check, thanks to the bridge, and was ignored. The reflection listing shows the bridge methods next to the declared ones.
Common questions
If the types are erased, how do frameworks like Jackson or Spring know the type argument of a field?
Generic signatures of fields, methods and superclasses are stored in the class file metadata and survive erasure. Reflection methods such as Field.getGenericType() return them. What is lost is the type argument of an individual object at run time. That's why libraries use tricks like an anonymous subclass of TypeReference<List<String>>, which records the type argument in its superclass signature.
Why do I sometimes see methods marked "synthetic" or "bridge" in stack traces?
The compiler generates bridge methods to keep overriding working after erasure, and covariant return types also need them. They show up as extra frames with the same method name. Method.isBridge() and Method.isSynthetic() identify them in reflection.
Can I overload methods that differ only in their type arguments, such as void f(List<String>) and void f(List<Integer>)?
No. Both erase to f(List), so the compiler reports a "name clash: have the same erasure" error. Give the methods different names.
Do the inserted casts make generic code slower?
Not measurably. A cast is a cheap check, and the JIT compiler removes many of them. Generic code performs the same as the hand-written Object-based code it replaced. The real cost of erasure today is boxing of primitives, which Project Valhalla aims to address.
Is it ever OK to use a raw type in new code?
Almost never. The main exception is class literals: you must write List.class, because List<String>.class is illegal. For type tests, instanceof List<?> works as well as the raw form. Use List<?> when you don't know the element type.
Summary
- The VM knows no generic types. Each generic class compiles to a single raw type.
- Type variables are erased to their first bound, or
Objectwithout a bound. Put marker interfaces last in bounds lists. - The compiler inserts casts when you read generic return values or fields.
- Generic methods are erased to a single method using the bounds.
- Bridge methods keep overriding polymorphic after erasure, including for covariant return types.
Method.isBridge()identifies them. - Passing generic types to legacy raw-type code compiles quietly, but receiving raw types gives unchecked warnings. Review them, then suppress them as narrowly as possible with
@SuppressWarnings("unchecked"). - Generic records support record patterns with inferred or explicit type arguments.
Practice Questions
What is the erasure of class Box<T extends Number & Comparable<T>> { T value; }?
class Box { Number value; }. T is replaced by its first bound, Number. Calls to compareTo get a cast to Comparable.
Why does the compiler insert a cast in String s = pairOfStrings.getFirst();?
The erased method getFirst returns Object, so the compiler adds a cast to String after the call. It is guaranteed to succeed if the program compiles without unchecked warnings.
Explain why DateInterval needs a bridge method setSecond(Object).
After erasure, Pair has setSecond(Object) while DateInterval declares setSecond(LocalDate), which doesn't override it. Calls through a Pair<LocalDate> variable compile to setSecond(Object). Without a bridge they'd run Pair's version and skip DateInterval's check. The bridge overrides setSecond(Object) and forwards to setSecond(LocalDate).
How can a class file contain two getSecond() methods with no parameters?
In the VM, a method is identified by name, parameter types and return type. LocalDate getSecond() and the bridge Object getSecond() differ in return type, which the VM allows, even though Java source code can't express it.
You assign a raw List from a legacy library to a List<String> variable. What happens at compile time and at run time?
Compile time: an unchecked conversion warning. Run time: nothing at the assignment. If the list actually contains non-strings, a ClassCastException occurs later, where an element is read as a String.
Does o instanceof Pair<String>(var a, var b) compile when o has static type Object?
No. The compiler can't check Pair<String> at run time, because the type argument is erased, so the cast from Object would be unchecked. Use o instanceof Pair<?>(String a, String b), which checks the component types instead.
Previous: Bounded Type Parameters in Java Generics: extends and Multiple Bounds
Next: Java Generics Inheritance Rules and Wildcards: extends, super and ?
Related reading

More in Core Java I
Java volatile, Atomics, Deadlocks and ThreadLocal: Safe Sharing Between Threads
Share data between Java threads without bugs: memory visibility and volatile, final fields, AtomicInteger and compareAndSet, LongAdder, lazy holder initialization, safe publication, lock-ordering deadlocks, ThreadLocal, InheritableThreadLocal and ScopedValue.
Java Condition Objects and the synchronized Keyword: await, signalAll, wait and notify
Make threads wait for a condition safely with Condition.await and signalAll, then learn Java's built-in alternative: synchronized methods and blocks, intrinsic locks, wait and notifyAll, choosing lock objects, client-side locking, and the monitor concept.
Java Race Conditions and ReentrantLock: Synchronizing Shared Data
Why unsynchronized threads corrupt shared data, shown step by step with a lost-update race, and how to fix it with ReentrantLock: the lock/try/finally idiom, critical sections, reentrancy and hold counts, tryLock, fair locks, and the mistakes that cause bugs.
Java invokeAll, invokeAny and Fork-Join: Running Groups of Tasks
Coordinate many concurrent tasks in Java: invokeAll to wait for every result, invokeAny to take the first success, timeouts, ExecutorCompletionService for results in completion order, structured concurrency, and the fork-join framework with RecursiveTask, RecursiveAction and work stealing.
Discussion
Sign in to ask a question or share what you learned.