Phase 15 of 20 · Topic 15.2

Type Erasure & Bytecode Translation

1Concept

Generics were added in Java 5 with backward compatibility in mind. The compiler applies Type Erasure: all generic type parameters are stripped in compiled bytecode and replaced by their bound (or `Object` if unbounded). Synthetic bridge methods are generated to preserve polymorphic method overriding.

2Architecture Diagram

Source:   public class Box<T> { T data; }
Bytecode: public class Box { Object data; } (Type parameter erased to Object!)

3Code Example

Core Java
import java.util.ArrayList;
import java.util.List;

public class TypeErasureDemo {
    public static void main(String[] args) {
        List<String> stringList = new ArrayList<>();
        List<Integer> intList = new ArrayList<>();

        // At runtime, both share the identical erased class!
        System.out.println("stringList.getClass() == intList.getClass(): " +
            (stringList.getClass() == intList.getClass()));
        System.out.println("Runtime Class Name: " + stringList.getClass().getName());
    }
}

4Expected Output

stringList.getClass() == intList.getClass(): true
Runtime Class Name: java.util.ArrayList

5Key Takeaways

  • Generic type information is unavailable at runtime via reflection on instance objects (due to erasure).
  • Method signatures with identical erased types (e.g. `test(List<String>)` vs `test(List<Integer>)`) cause compilation errors.
  • Subclasses retaining generic parameters preserve type metadata in the `Signature` attribute (accessible via TypeTokens).