Java Type Erasure

Su Suriya Ravichandran Updated 18 Nov 2026
10 min read ·Lesson 164 of 306

What Type Erasure Is

Java's generics are checked by the compiler and then mostly removed from the compiled bytecode. This process is called type erasure:

  1. The compiler checks all generic code for type safety.
  2. It then replaces each type parameter with its bound — Object for an unbounded T, Number for T extends Number.
  3. It inserts casts where values come out of generic code, and generates bridge methods where needed to keep polymorphism working.

At runtime, the JVM sees ordinary classes. List<String> and List<Integer> are both just List.

Why Java did it this way: generics arrived in Java 5, ten years after Java 1.0. Erasure meant that generic code compiled to the same bytecode format as before, ran on the existing JVM, and worked together with the huge amount of existing non-generic code and libraries (migration compatibility). The price is a set of restrictions that every Java developer runs into sooner or later — this lesson explains where they come from.

Seeing Erasure

Same class at runtime

import java.util.*;

public class Same {
    public static void main(String[] args) {
        List<String> names = new ArrayList<>();
        List<Integer> ages = new ArrayList<>();
        System.out.println(names.getClass() == ages.getClass());
        System.out.println(names.getClass().getName());
        System.out.println(names instanceof ArrayList<?>);
    }
}

Output:

true
java.util.ArrayList
true

There is only one ArrayList class. The object doesn't remember whether it was created as a list of strings or of integers.

The compiled signatures

Given this class:

public class Box<T> {
    private T value;
    public void set(T value) { this.value = value; }
    public T get() { return value; }
}

the javap tool (included with the JDK) shows the compiled method descriptors — the signatures the JVM actually uses:

$ javap -s Box
public class Box<T> {
  public Box();
    descriptor: ()V

  public void set(T);
    descriptor: (Ljava/lang/Object;)V

  public T get();
    descriptor: ()Ljava/lang/Object;
}

The source-level signatures (set(T), T get()) are kept as metadata, but the descriptors say Object: set takes an Object and get returns an Object. For a bounded type, the bound is used instead:

$ javap -s Bounded         (class Bounded<T extends Number> { public T get() ... })
  public T get();
    descriptor: ()Ljava/lang/Number;

The inserted cast

For code that uses Box<String>:

public class UseBox {
    public static void main(String[] args) {
        Box<String> b = new Box<>();
        b.set("Java");
        String s = b.get();
        System.out.println(s.length());
    }
}

javap -c UseBox shows the bytecode the compiler generated:

      11: invokevirtual #12                 // Method Box.set:(Ljava/lang/Object;)V
      14: aload_1
      15: invokevirtual #16                 // Method Box.get:()Ljava/lang/Object;
      18: checkcast     #20                 // class java/lang/String
      21: astore_2

get() returns an Object, and the compiler inserted a checkcast to String — exactly the cast you'd have written by hand before Java 5. Generics didn't remove the casts; they moved them into code the compiler writes for you, after first proving they're safe.

Consequences of Erasure

Most generic restrictions follow directly from "the type argument doesn't exist at runtime":

RestrictionReason
No new T() or new T[n]The JVM doesn't know which class T is
No obj instanceof List<String> (only List<?>)The object doesn't record its type argument
No primitive type arguments (List<int>)Erasure replaces T with Object (or a bound), and primitives aren't objects
A class can't implement both Comparable<A> and Comparable<B>After erasure, both are the same interface
Static fields can't use TThere is one class (and one set of static fields) for all type arguments
Overloads can't differ only in type argumentsTheir erased signatures are identical — shown next
Casts to generic types are uncheckedThe JVM can check (List) o, not (List<String>) o
Generic exception classes aren't allowed (class MyEx<T> extends Exception)A catch clause needs a runtime type to match

Overloads that erase to the same signature

import java.util.*;

public class Clash {
    void print(List<String> names) { }
    void print(List<Integer> numbers) { }
}
Clash.java:5: error: name clash: print(List<Integer>) and print(List<String>) have the same erasure
    void print(List<Integer> numbers) { }
         ^
1 error

After erasure, both methods would be print(List), and the JVM couldn't tell them apart. Use different method names (printNames, printNumbers) or a single generic method instead.

Bridge Methods

Erasure creates a problem for polymorphism, which the compiler solves with bridge methods:

import java.lang.reflect.*;
import java.util.*;

public class Bridge {
    record Course(String code, int fee) implements Comparable<Course> {
        @Override public int compareTo(Course other) { return Integer.compare(fee, other.fee); }
    }

    public static void main(String[] args) {
        for (Method m : Course.class.getDeclaredMethods()) {
            if (m.getName().equals("compareTo")) {
                System.out.println(m.getName() + "(" + m.getParameterTypes()[0].getSimpleName() + ") bridge=" + m.isBridge());
            }
        }
        List<Course> list = new ArrayList<>(List.of(new Course("DJ", 5999), new Course("PY", 2999)));
        Collections.sort(list);
        System.out.println(list);
    }
}

Output (the order in which reflection lists methods isn't guaranteed):

compareTo(Object) bridge=true
compareTo(Course) bridge=false
[Course[code=PY, fee=2999], Course[code=DJ, fee=5999]]

After erasure, the Comparable interface declares compareTo(Object). Course declares compareTo(Course), which, at the bytecode level, is a different method. Code like Collections.sort calls compareTo(Object) through the interface, so the compiler adds a hidden bridge method compareTo(Object) that casts its argument to Course and calls your compareTo(Course). Reflection shows both; isBridge() identifies the synthetic one.

You rarely need to think about bridge methods, but they explain two things you might see: extra methods in stack traces and reflection output, and a ClassCastException thrown from a line where you don't see any cast — the bridge's hidden cast failed because a wrong type got in through an unchecked operation.

Heap Pollution from Unchecked Casts

Because a cast to a generic type can't be checked at runtime, it's possible to trick the type system — with an @SuppressWarnings("unchecked") that hides the compiler's warning:

import java.util.*;

public class Pollute {
    @SuppressWarnings("unchecked")
    static <T> List<T> unsafeCast(Object o) {
        return (List<T>) o;
    }

    public static void main(String[] args) {
        List<Integer> ids = new ArrayList<>(List.of(101, 102));
        List<String> names = unsafeCast(ids);
        System.out.println("cast succeeded, size " + names.size());
        names.add("Asha");
        System.out.println("ids now: " + ids);
        int first = ids.get(0);
        System.out.println("first id: " + first);
        int third = ids.get(2);
    }
}

Output:

cast succeeded, size 2
ids now: [101, 102, Asha]
first id: 101
Exception in thread "main" java.lang.ClassCastException: class java.lang.String cannot be cast to class java.lang.Integer (java.lang.String and java.lang.Integer are in module java.base of loader 'bootstrap')
	at Pollute.main(Pollute.java:17)
  • The cast (List<T>) o only checks that o is a List — which it is — so it succeeds. The compiler would normally warn "unchecked cast"; the annotation silenced it.
  • names and ids now refer to the same list. Adding "Asha" through names puts a String into the List<Integer>.
  • Reading the first element works. Reading the third fails at line 17 — far from the real mistake — because the compiler-inserted checkcast to Integer finally meets the string.

This is heap pollution. The lesson: an unchecked warning means the compiler can no longer guarantee type safety. Suppress one only when you've proven the cast is correct, put the @SuppressWarnings on the smallest possible scope, and add a comment explaining why it's safe.

What Survives Erasure

Erasure removes type arguments from objects, but generic information written in declarations is kept in the class file as metadata and can be read through reflection:

import java.lang.reflect.*;
import java.util.*;

public class Kept {
    static class Catalog {
        private Map<String, List<Integer>> pricesByCourse = new HashMap<>();
        public List<String> titles() { return List.of(); }
    }

    public static void main(String[] args) throws Exception {
        Field f = Catalog.class.getDeclaredField("pricesByCourse");
        System.out.println("field type:         " + f.getType().getName());
        System.out.println("generic field type: " + f.getGenericType());
        Method m = Catalog.class.getMethod("titles");
        System.out.println("generic return:     " + m.getGenericReturnType());

        List<Integer> local = new ArrayList<>();
        System.out.println("object's class:     " + local.getClass().getTypeName());
    }
}

Output:

field type:         java.util.Map
generic field type: java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>
generic return:     java.util.List<java.lang.String>
object's class:     java.util.ArrayList
  • The declared types of fields, method parameters and return types, and the type arguments in extends/implements clauses, are available through getGenericType(), getGenericReturnType(), getGenericSuperclass() and similar methods, which return java.lang.reflect.Type objects such as ParameterizedType.
  • The object itself still doesn't know its type argument: local.getClass() is just ArrayList.

This is how frameworks like Jackson, Gson, Hibernate and Spring know that a field declared List<Address> should be filled with Address objects: they read the declaration, not the object.

Practical Example: Type Tokens for a Configuration Reader

A configuration reader should convert text values into whatever type the caller needs — int, boolean, Duration, even List<Integer>. Because of erasure, a generic method can't find out what T is from the call alone; the caller must pass the type as a runtime object, a type token. A Class<T> works for simple types. For generic types like List<Integer>, there is no List<Integer>.class, so the super type token trick captures the full type through an anonymous subclass's declaration — one of the declarations that survives erasure.

import java.lang.reflect.*;
import java.util.*;
import java.util.function.Function;

public class Config {
    abstract static class TypeRef<T> {
        final Type type;
        protected TypeRef() {
            Type superType = getClass().getGenericSuperclass();
            this.type = ((ParameterizedType) superType).getActualTypeArguments()[0];
        }
    }

    static final Map<Class<?>, Function<String, ?>> PARSERS = Map.of(
        String.class, s -> s,
        Integer.class, Integer::valueOf,
        Boolean.class, Boolean::valueOf,
        Double.class, Double::valueOf,
        java.time.Duration.class, java.time.Duration::parse);

    private final Map<String, String> raw;
    Config(Map<String, String> raw) { this.raw = raw; }

    <T> T get(String key, Class<T> type) {
        String text = Objects.requireNonNull(raw.get(key), "missing key " + key);
        Function<String, ?> parser = PARSERS.get(type);
        if (parser == null) throw new IllegalArgumentException("no parser for " + type.getSimpleName());
        return type.cast(parser.apply(text.strip()));
    }

    @SuppressWarnings("unchecked")
    <T> T get(String key, TypeRef<T> ref) {
        if (ref.type instanceof ParameterizedType p && p.getRawType() == List.class) {
            Class<?> element = (Class<?>) p.getActualTypeArguments()[0];
            List<Object> items = new ArrayList<>();
            for (String part : raw.get(key).split(",")) {
                items.add(PARSERS.get(element).apply(part.strip()));
            }
            return (T) List.copyOf(items);
        }
        throw new IllegalArgumentException("unsupported type " + ref.type);
    }

    public static void main(String[] args) {
        Config cfg = new Config(Map.of(
            "server.port", "8080", "feature.newCheckout", "true",
            "session.timeout", "PT30M", "retry.delays", "100, 200, 400",
            "admin.emails", "asha@gocourse.in, ravi@gocourse.in"));

        int port = cfg.get("server.port", Integer.class);
        boolean newCheckout = cfg.get("feature.newCheckout", Boolean.class);
        java.time.Duration timeout = cfg.get("session.timeout", java.time.Duration.class);
        System.out.println(port + 1 + " " + newCheckout + " " + timeout.toMinutes() + " min");

        TypeRef<List<Integer>> listOfInts = new TypeRef<>() { };
        System.out.println("captured type: " + listOfInts.type);
        List<Integer> delays = cfg.get("retry.delays", listOfInts);
        System.out.println("total delay: " + delays.stream().mapToInt(Integer::intValue).sum() + " ms");
        List<String> admins = cfg.get("admin.emails", new TypeRef<List<String>>() { });
        System.out.println("first admin: " + admins.get(0).toUpperCase());
    }
}

Output:

8081 true 30 min
captured type: java.util.List<java.lang.Integer>
total delay: 700 ms
first admin: ASHA@GOCOURSE.IN

How it works:

  1. Class<T> as a token. get("server.port", Integer.class) passes the class object, which exists at runtime. The method uses it to look up a parser, and type.cast(...) performs a checked cast that returns a T — so int port = ... compiles without any unchecked warnings.
  2. A parser table. Map<Class<?>, Function<String, ?>> maps each supported type to a conversion function. Duration::parse understands ISO-8601 durations such as PT30M (30 minutes).
  3. The super type token. new TypeRef<List<Integer>>() { } creates an anonymous subclass whose declaration is extends TypeRef<List<Integer>>. That declaration is stored in the class file. The constructor calls getClass().getGenericSuperclass(), gets a ParameterizedType, and extracts the actual type argument: java.util.List<java.lang.Integer> — the full generic type, recovered despite erasure. The { } is essential; without it, there's no subclass and no stored declaration (and the abstract class couldn't be instantiated anyway).
  4. Using the captured type. The second get checks that the token is a parameterized List, extracts the element class (Integer or String), parses each comma-separated part with the matching parser, and returns an unmodifiable list.
  5. One justified unchecked cast. The final (T) List.copyOf(items) can't be checked by the JVM, but the method has built the list from exactly the element type the token describes, so the cast is correct. The @SuppressWarnings is limited to this method for that reason.

This is the technique behind Jackson's TypeReference (mapper.readValue(json, new TypeReference<List<Order>>() {})), Gson's TypeToken and Spring's ParameterizedTypeReference — whenever a library must produce a generic type such as List<Order> at runtime, you'll see an anonymous subclass with {} at the end.

0 Comments

Reviewed before they appear

No comments yet.

Java
Java Introduction Java Features Java Syntax Java Comments Java Statements Java Output Java Variables Java Data Types Java Type Casting Java Operators Java Strings Java Numbers Java Math Java Booleans Java User Input Java Conditions Java If Else Java Switch Java While Loop Java For Loop Java Break Java Continue Java Arrays Java Methods Java Parameters Java Return Values Java Scope Java Recursion Install Java Install JDK Java IDEs Java JDK Java JRE Java JVM Java Compiler Java File Compile Java Run Java JShell Basics Java Packages Java OOP Java Classes Java Objects Class Methods Constructors Constructor Overload this Keyword static Keyword final Keyword Encapsulation Inheritance Polymorphism Abstraction Access Modifiers super Keyword Method Overload Method Override Instanceof Operator Nested Classes Inner Classes Anonymous Classes Enums Records Array Basics Array Length Loop Arrays Multidimensional Arrays Array Copy Array Sorting Array Search ArrayList LinkedList HashSet TreeSet HashMap TreeMap Queue Interface Deque Interface Stack Class Iterator List Interface Set Interface Map Interface Collections Class Comparable Comparator Generics Basics Generic Classes Generic Methods Wildcards String Basics String Length String Methods String Concatenation String Compare String Search String Replace String Split String Format StringBuilder StringBuffer Text Blocks Regular Expressions Number Types Integer Class Float Class Double Class BigInteger BigDecimal Math Class Random Numbers Number Format Date Basics LocalDate LocalTime LocalDateTime ZonedDateTime Date Formatting Date Parsing Period Class Duration Class Java Instant Class Java Exception Basics Java try...catch Java Multiple Catch Blocks Java finally Block Java throw Keyword Java throws Keyword Java Checked Exceptions Java Unchecked Exceptions Java Custom Exceptions Java try-with-resources Java Exception Chaining Java File Basics Java Create Files Java Read Files Java Write Files Java Delete Files Java File Paths Java File Class Java BufferedReader Java BufferedWriter Java FileInputStream Java FileOutputStream Java Object Streams Java Directory Handling Java NIO Basics Java Files API Java Input Java Scanner Class Java Console Input Java PrintStream Java InputStream Java OutputStream Java Reader Class Java Writer Class Java Buffered Streams Java Data Streams Java Generics Introduction Java Generic Types Java Generic Methods Java Bounded Types Java Wildcards Java Type Erasure Java Generic Interfaces Java Generic Collections Java Lambda Basics Java Lambda Syntax Java Functional Interfaces Java Method References Java Stream API Java Stream Creation Java Stream Filter Java Stream Map Java Stream Reduce Java Stream Sort Java Stream Collect Java Collectors Class Java Optional Class Java Parallel Streams Java Threads: Thread Basics Create a Thread in Java Java Thread Class Java Runnable Interface Java Thread States Java Thread Sleep Java Thread Join Java Thread Priority Java Synchronization Java Thread Safety Java Race Conditions Java Deadlocks Java Executor Service Java Thread Pools Java Callable Interface Java Future Interface Java CompletableFuture Java Concurrent Collections Java Atomic Classes Java Virtual Threads Java Networking Basics Java URL Class Java URI Class Java HttpClient Java HTTP Requests Java HTTP Responses Java Socket Basics Java ServerSocket Java DatagramSocket Java WebSocket Basics Java JDBC Basics Java JDBC Setup Java Database Connection Java JDBC Connection Interface Java JDBC Statement Java PreparedStatement Java ResultSet Java JDBC CRUD Operations Java JDBC Transactions Java JDBC Batch Update Java Connection Pooling with HikariCP Java JPA Basics: Entities, EntityManager and JPQL Java Hibernate Basics: SessionFactory, Session and HQL Package in Java: Basics Explained with Examples Create Package in Java: Step-by-Step Guide with Examples Import Package in Java: The import Statement Explained Access Control in Java: Packages, Classes and Members JAR File in Java: Create, Run and Inspect JAR Files Java Modules: Introduction to the Java Module System module-info in Java: Every Module Directive Explained Java Module Path: How --module-path Finds Your Modules Java Classpath: How -cp and CLASSPATH Find Your Classes Java Annotations: Basics of @ Metadata in Java Java Built-in Annotations: @Override, @Deprecated and More Java Custom Annotations: Create Your Own @interface Java Annotation Targets: @Target and ElementType Explained Java Reflection API: Inspect and Use Classes at Runtime Java Class Metadata: Names, Modifiers, Hierarchy and Generic Java Dynamic Objects: Create Objects Dynamically With Reflec Java Dynamic Proxy: Intercept Method Calls With Proxy and In Java Security Java Secure Coding Java Password Hashing Java Input Validation Java Cryptography Basics Java KeyStore Basics Java TLS Basics Java SecureRandom Java JUnit Basics Java JUnit Test Methods JUnit Assertions JUnit Test Fixtures JUnit Parameterized Tests Mockito in Java Java Mock Objects Java Integration Testing Java Code Coverage Maven in Java Create a Maven Project in Java Maven Dependencies Maven Plugins Gradle in Java Gradle Build Gradle Dependencies Build Executable JAR in Java Build WAR File in Java HTTP Basics in Java Java Servlet Basics Servlet Lifecycle in Java HttpServletRequest in Java HttpServletResponse in Java JSP in Java JSTL in JSP REST API in Java JSON in Java Java Web Application Spring Framework Basics Spring Boot Tutorial Spring MVC Spring Data JPA Spring Security Spring Boot REST API Jakarta EE Basics Java Deployment JAR Deployment Java WAR Deployment Run Java as a Service Docker Java: Dockerize a Java Application Java Environment Variables and Configuration Java Logging Basics Java Production Setup Java JVM Options Java JVM Monitoring Java Hello World App Java Calculator App Java Number Guess Game Java Student Manager Java Library System Java Bank App Java Todo App Java File Manager Java Quiz App Java REST API Project Java Chat Server Java Employee Manager Java E-commerce API
Ask about this post
AI Ask about this post

Ask questions about Java Type Erasure and get answers drawn from it.

Signed-in readers only.