Skip to content
notes.vinhnq.com

Search

Java CoreSenior21 min read

Java generics: type erasure, raw types and type tokens

Review 14 cards
On this page

Java generics series: 1. Generic classes, methods, bounded types · 2. Wildcards and PECS · 3. Type erasure and type tokens

Parts 1 and 2 were about what generics check at compile time. Part 3 answers the follow-up senior interviews love: what’s left of generics at runtime? After reading, you can explain type erasure and its consequences, get the type back at runtime with type tokens, and use generics with records and sealed interfaces (Java 17–21).

Read part 1 (generic classes and methods, invariance) and part 2 (wildcards, PECS) first.

At a glance:

flowchart LR
  S["List#lt;String#gt;"] -->|compiler checks| E[Erasure]
  E --> B["T → bound/Object + cast"]
  E --> BR[Bridge method]
  E --> RT["Runtime: one class"]
  RT --> L["No new T(), List#lt;int#gt;, instanceof"]
  E --> D["Declarations kept in .class"]
  D --> TT[Type token]
  RAW["Raw type / unchecked cast"] -.->|trap| CCE["ClassCastException at read site"]

1. Type erasure

Key idea: Java implements generics with type erasure: the compiler type-checks with full information, then drops the type arguments from the bytecode. Almost every “weird” limitation of generics follows from that one decision.

1.1. What the compiler does with generics

At compile time, javac does four things:

  1. Type-checks with full generic information.
  2. Replaces each type parameter with its erasure: the first bound if there is one (<T extends Number> becomes Number), otherwise Object. List<String> becomes List.
  3. Inserts checkcast (the bytecode instruction for a checked cast) wherever a value has to be turned back into a specific type.
  4. Generates bridge methods where needed to keep polymorphism working (1.3).

At runtime, ArrayList<String> and ArrayList<Integer> are the same class:

new ArrayList<String>().getClass() == new ArrayList<Integer>().getClass()   // true

Java chose erasure for backward compatibility with pre-Java 5 code. The price is the limitations in 1.2.

Bytecode javap -c after erasure and why Java doesn’t keep types like C#

Here’s String first(List<String> l) { return l.get(0); } after compilation, viewed with javap -c:

invokeinterface #7,  2   // InterfaceMethod java/util/List.get:(I)Ljava/lang/Object;
checkcast       #13      // class java/lang/String

At the bytecode level List.get returns Object; the cast to String was inserted by the compiler.

Why did Java choose erasure instead of keeping types at runtime like C#? Generics arrived in Java 5 (2004), when there were already millions of lines of code using non-generic collections. Erasure let old and new code, and old and new libraries, run together without recompiling and without changing the JVM.

1.2. Consequences of erasure

You can’t Why What to do instead
List<int> The erasure is Object, and a primitive isn’t an Object List<Integer> (boxing), or IntStream, int[], a primitive collections library
new T() At runtime nobody knows which class T is Pass a Supplier<T> or a Class<T>
new T[n], new List<String>[n] Arrays need a real element type at runtime Array.newInstance(type, n), toArray(String[]::new), or just use a List
obj instanceof List<String> (with obj typed as Object) The runtime can’t tell List<String> from List<Integer> obj instanceof List<?>, then check elements if you must
static T field A static field is shared by every Box<String>, Box<Integer>, … Move T to a static generic method
class MyEx<T> extends Exception, catch (T e) catch is decided at runtime by the actual type A non-generic exception that carries data in fields
Overloading f(List<String>) and f(List<Integer>) Both methods erase to f(List) Give them different names
The Java 16 instanceof exception and the same-erasure overload error

Since Java 16, pattern matching allows instanceof List<String> ls when the compiler can prove it’s safe, i.e. the static type is already Collection<String> or List<String>. On an Object it’s still an error: Object cannot be safely cast to List<String>.

1.3. Bridge methods

Erasure can break overriding. Consider:

public final class Name implements Comparable<Name> {
    private final String value;
    public Name(String value) { this.value = value; }

    @Override
    public int compareTo(Name other) { return value.compareTo(other.value); }
}

After erasure, Comparable declares compareTo(Object), while the class has compareTo(Name). Different signatures, so strictly speaking the class no longer overrides the interface method.

The compiler patches this with a bridge method (marked synthetic, i.e. compiler-generated): compareTo(Object) casts its argument to Name and calls compareTo(Name). Two consequences:

  • Call through a raw type with the wrong argument and the ClassCastException comes from the bridge, a line you never wrote.
  • That’s why Method.isBridge() exists. Reflection-heavy frameworks (Spring, Hibernate, Jackson) filter bridges out so they don’t process the same method twice.
Bridge method seen with javap -p and the ClassCastException thrown by the bridge
$ javap -p Name
public final class Name implements java.lang.Comparable<Name> {
  public int compareTo(Name);
  public int compareTo(java.lang.Object);     // bridge: checkcast Name, then call compareTo(Name)
}

Calling through a raw type with the wrong argument:

Comparable raw = new Name("a");
raw.compareTo("x");   // ClassCastException: String cannot be cast to Name (thrown by the bridge)

1.4. Heap pollution and @SafeVarargs

Heap pollution happens when a variable of a parameterized type (say List<String>) refers to an object that isn’t actually of that type. The compiler emits an unchecked warning whenever this is possible. The real failure shows up later, at a compiler-inserted cast.

The most common sources are raw types (section 2) and generic varargs. Varargs are implemented with an array, and since a real T[] can’t be created, the compiler creates an array of the erasure:

static <T> T[] toArray(T... args) { return args; }      // warning: possible heap pollution

static <T> T[] pickTwo(T a, T b, T c) {
    return toArray(a, b);   // T erases to Object -> always creates an Object[]
}

String[] two = pickTwo("a", "b", "c");
// ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.String;

Inside pickTwo, the compiler doesn’t know what T is, so the varargs array is an Object[]. That array escapes to the caller, gets cast to String[], and blows up. So: never return a generic varargs array and never write into it.

@SafeVarargs is the method author’s promise:

  • The method doesn’t write to the varargs array and doesn’t leak a reference to it. With that promise, the warning at call sites goes away.
  • It can only go on methods that can’t be overridden: static, final, private (since Java 9) and constructors.
  • List.of(E...), Set.of(E...), Arrays.asList(T...) and Stream.of(T...) all carry @SafeVarargs.
@SafeVarargs used correctly and the trap of returning the varargs array
@SafeVarargs
static <T> List<T> listOf(T... items) {
    return List.of(items);    // only reads the array; List.of copies into its own structure
}

1.5. Erasure doesn’t erase everything

A common misconception (beginner material often states it this way) is that “all generic information is wiped at runtime”. In reality:

  • An object doesn’t know its type arguments.
  • Declarations keep them: the generic signatures of classes, fields, methods and supertypes are stored in the Signature attribute of the .class file and can be read through reflection.
class Holder {
    Map<String, List<Integer>> data;
}

Field f = Holder.class.getDeclaredField("data");
System.out.println(f.getGenericType());
// java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>

This is what type tokens in section 4 are built on. Spring knows which bean to inject into a Repository<User> by reading the same declaration metadata.

2. Raw types

Key idea: a raw type is a generic type’s name used without type arguments (List, Map, Comparable), and exists only for compatibility with pre-Java 5 code. Using one turns off all generic checking for that variable.

A raw type can even corrupt a collection that’s still referenced through a correctly typed variable:

List<String> strings = new ArrayList<>();
List raw = strings;          // allowed, no warning
raw.add(42);                 // unchecked warning, but it runs
System.out.println(strings.size());   // 1

String s = strings.get(0);   // ClassCastException here, far from the cause

A few places where raw types are legitimate and unavoidable:

  • Class literals: List.class (there’s no List<String>.class).
  • instanceof (though instanceof List<?> states the intent more clearly).
  • Interop with old, non-generic libraries.

When you’re forced to work with type-unsafe code:

  • Turn on -Xlint:unchecked.
  • Keep @SuppressWarnings("unchecked") to the smallest possible scope: a single local variable, with a comment explaining why it’s safe.
  • For collections that receive data from untrusted code, wrap them with Collections.checkedList(list, String.class) so the type is checked at add time.

3. Reifiable types

Key idea: a type is reifiable if its full type information is available at runtime. Arrays, instanceof and checked casts only work with reifiable types.

Reifiable types are:

  • Primitive types (int) and non-generic types (String, Number).
  • Raw types (List).
  • Parameterized types made only of unbounded wildcards (List<?>, Map<?, ?>).
  • Arrays whose element type is reifiable (String[], List<?>[]).

Not reifiable: List<String>, T, List<? extends Number>, Map<String, T>.

This one concept ties together rules that otherwise look unrelated:

  • Arrays can only be created with a reifiable element type, because the array has to perform the ArrayStoreException check at runtime: new List<?>[10] is fine, new List<String>[10] isn’t.
  • A cast to a non-reifiable type ((List<String>) obj) is an unchecked cast.
  • Varargs of a non-reifiable type trigger the heap pollution warning.

4. Getting the type back at runtime: type tokens

Key idea: when a method genuinely needs the type at runtime (to create an object, create an array, deserialize JSON), pass the type in as a value. There are three ways: Class<T>, Supplier<T> and a super type token.

Class token: pass a Class<T>.

static <T> T[] newArray(Class<T> type, int size) {
    @SuppressWarnings("unchecked")   // safe: Array.newInstance creates a real T[]
    T[] array = (T[]) Array.newInstance(type, size);
    return array;
}

String[] names = newArray(String.class, 3);

Class<T> gives you type.cast(obj) (a checked cast) and type.isInstance(obj). The JDK uses this pattern in EnumMap(Class<K>), Collections.checkedList(list, Class<E>) and ServiceLoader.load(Class<S>).

Factory: instead of new T(), accept a Supplier<T>. It’s simpler than reflection and lets you pass constructors that take arguments.

static <T> T create(Supplier<? extends T> factory) { return factory.get(); }

StringBuilder sb = create(StringBuilder::new);
String[] arr = List.of("a", "b").toArray(String[]::new);   // IntFunction<T[]> is a factory too

Super type token: a Class<T> can’t represent List<User> (there’s only List.class). Neal Gafter’s trick: create an anonymous subclass of an abstract generic class. The anonymous class’s supertype is recorded in its .class file (section 1.5), so you can read it back. Real libraries use this exact pattern:

// Jackson
List<User> users = objectMapper.readValue(json, new TypeReference<List<User>>() {});

// Spring RestClient / RestTemplate / WebClient
List<User> users = restClient.get().uri("/users")
        .retrieve()
        .body(new ParameterizedTypeReference<List<User>>() {});

// Gson
Type listType = new TypeToken<List<User>>() {}.getType();

The trailing {} is mandatory: it’s what creates the anonymous subclass. Leave it out and the code doesn’t compile (the class is abstract), so this pattern can’t be misused silently.

Writing your own super type token: TypeRef<T> in ten lines
public abstract class TypeRef<T> {
    private final Type type;

    protected TypeRef() {
        ParameterizedType superType = (ParameterizedType) getClass().getGenericSuperclass();
        this.type = superType.getActualTypeArguments()[0];
    }

    public Type type() { return type; }
}

Type t = new TypeRef<Map<String, List<Integer>>>() {}.type();
// java.util.Map<java.lang.String, java.util.List<java.lang.Integer>>

The constructor reads the generic supertype of the anonymous class itself (getGenericSuperclass()), then takes the first type argument.

5. Generics with records and sealed interfaces

Key idea: a sealed interface plus generic records gives you a sum type (a value that is exactly one of a few fixed shapes) like Result<T>. The compiler checks that a switch covers every shape. Records and sealed interfaces arrived in Java 17, record patterns in switch in Java 21.

Example: a result that’s either a success or a failure:

public sealed interface Result<T> permits Ok, Err {}
public record Ok<T>(T value) implements Result<T> {}
public record Err<T>(String message) implements Result<T> {}

static String describe(Result<Integer> result) {
    return switch (result) {
        case Ok<Integer>(Integer v) when v > 100 -> "big " + v;
        case Ok(var v) -> "ok " + v;              // Java 21 infers Ok<Integer>
        case Err(var message) -> "error: " + message;
    };
}

Things worth noticing:

  • The switch is exhaustive (covers every case): Result is sealed with exactly two subtypes, so no default is needed. Add a new subtype to permits and every switch missing that case fails to compile, exactly where you need to look.
  • Record patterns infer type arguments: case Ok(var v) is understood as Ok<Integer>, and v is an Integer.

This pattern shows up a lot in backend code: validation results, results of calls to external services, events in event sourcing (sealed interface OrderEvent), response wrappers like ApiResponse<T>.

Generic record Pair<A, B>, a note on Err<T> and everyday generics in Spring

Err<T> doesn’t use T in any field, but it still needs the T to be a Result<T>. If you want typed errors too, use Result<T, E> (exercise 1 builds on this).

Generic record: a pair of values without hand-written equals/hashCode/toString:

public record Pair<A, B>(A first, B second) {
    public static <A, B> Pair<A, B> of(A first, B second) { return new Pair<>(first, second); }

    public <C> Pair<A, C> withSecond(C newSecond) { return new Pair<>(first, newSecond); }
}

Pair<String, Integer> p = Pair.of("age", 30);
Pair<String, Boolean> q = p.withSecond(true);

In Spring you use generics every day without thinking about it: JpaRepository<User, Long> (see ORM and JPA), ResponseEntity<UserDto>, Optional<T>, Page<T>.

Spring also injects by generic type: if Validator<User> and Validator<Order> are two beans, @Autowired Validator<User> v gets the right one, by reading the declaration metadata from section 1.5 (see IoC and Dependency Injection).

Exercises

Exercise 1: Result<T> with map and flatMap

Task: extend the sealed Result<T> from section 5 with map, flatMap and orElse, then use it to parse a string into a positive number and double it, without using exceptions to report failures.

Solution to exercise 1: Result<T> with map, flatMap, orElse
sealed interface Result<T> permits Result.Ok, Result.Err {
    record Ok<T>(T value) implements Result<T> {}
    record Err<T>(String error) implements Result<T> {}

    static <T> Result<T> ok(T value) { return new Ok<>(value); }
    static <T> Result<T> err(String error) { return new Err<>(error); }

    default <R> Result<R> map(Function<? super T, ? extends R> f) {
        return switch (this) {
            case Ok<T>(T v) -> new Ok<>(f.apply(v));
            case Err<T>(String e) -> new Err<>(e);
        };
    }

    default <R> Result<R> flatMap(Function<? super T, ? extends Result<? extends R>> f) {
        return switch (this) {
            case Ok<T>(T v) -> narrow(f.apply(v));
            case Err<T>(String e) -> new Err<>(e);
        };
    }

    default T orElse(T fallback) {
        return this instanceof Ok<T>(T v) ? v : fallback;
    }

    // Safe because Result is immutable: it only hands T out, it never accepts a T
    @SuppressWarnings("unchecked")
    private static <R> Result<R> narrow(Result<? extends R> r) { return (Result<R>) r; }
}

static Result<Integer> parse(String s) {
    try { return Result.ok(Integer.parseInt(s)); }
    catch (NumberFormatException e) { return Result.err("not a number: " + s); }
}
static Result<Integer> positive(int n) {
    return n > 0 ? Result.ok(n) : Result.err("not positive: " + n);
}

parse("42").flatMap(Main::positive).map(n -> n * 2);    // Ok[value=84]
parse("-3").flatMap(Main::positive).map(n -> n * 2);    // Err[error=not positive: -3]
parse("abc").flatMap(Main::positive).map(n -> n * 2);   // Err[error=not a number: abc]
Result<Number> widened = parse("5").flatMap(Main::positive);   // works thanks to ? extends R

About the signatures:

  • Function<? super T, ? extends R> is PECS (the function consumes a T and produces an R).
  • flatMap takes a function returning Result<? extends R> so that a function returning Result<Integer> can be used where a Result<Number> is needed.
  • The cast in narrow is unchecked but safe because Result is immutable and only ever “produces” T. That’s exactly the reasoning languages with declaration-site variance (Kotlin’s out T) let the compiler do for you.

Exercise 2: A type-safe heterogeneous container

Task: write a Context that stores values of different types (retry count as an Integer, user as a String, …) so that reading them needs no cast and can’t return the wrong type.

The idea (from Effective Java, the “typesafe heterogeneous container”): put the type parameter on the key instead of on the container.

Solution to exercise 2: Key<T> and Context
final class Key<T> {
    final String name;
    final Class<T> type;

    private Key(String name, Class<T> type) { this.name = name; this.type = type; }

    static <T> Key<T> of(String name, Class<T> type) { return new Key<>(name, type); }
}

final class Context {
    private final Map<Key<?>, Object> values = new HashMap<>();

    <T> void put(Key<T> key, T value) {
        values.put(key, key.type.cast(value));   // checked cast, stops raw-type tricks
    }

    <T> Optional<T> get(Key<T> key) {
        return Optional.ofNullable(key.type.cast(values.get(key)));
    }
}

Key<Integer> RETRIES = Key.of("retries", Integer.class);
Key<String> USER = Key.of("user", String.class);

Context ctx = new Context();
ctx.put(RETRIES, 3);
ctx.put(USER, "vinh");
int retries = ctx.get(RETRIES).orElse(0);   // no cast
// ctx.put(RETRIES, "three");               // compile error

The internal Map<Key<?>, Object> isn’t type-safe, but the public API guarantees each value always matches its key’s type, and Class.cast double-checks at runtime. Spring uses a similar idea in AttributeAccessor, Netty in AttributeKey<T>, Reactor in its Context.

Remember

  • Explain the four things the compiler does with generics, and why Java chose erasure.
  • Name at least five things erasure forbids, with the workaround for each.
  • Explain why a ClassCastException can come from a line you never wrote (bridge methods, compiler-inserted casts).
  • Know when Class<T> or Supplier<T> is enough, when you need a TypeReference, and why the {} is required.
  • Know when @SafeVarargs is allowed, and when to choose a sealed Result<T> over exceptions.

Interview questions

Junior

Why can’t you write List<int>?

Because of type erasure: type parameters are replaced by Object (or their bound), and int isn’t an Object.

You use the wrapper List<Integer> (paying for boxing, with each element a separate heap object). When performance matters, use int[], IntStream or a primitive collections library.

Mid

What is type erasure and what limitations does it bring?

The compiler type-checks with full information, then removes the type arguments: it replaces T with its bound (or Object), inserts casts and generates bridge methods.

Consequences:

  • No List<int>, no new T(), no new T[].
  • No instanceof List<String> on an Object, no static T field, no generic exceptions.
  • No overloads that differ only by type argument.
  • ArrayList<String>.class == ArrayList<Integer>.class.

Erasure was chosen for backward compatibility with pre-Java 5 code without changing the JVM.

What is a bridge method and when does the compiler generate one?

A synthetic method the compiler adds to keep polymorphism working after erasure.

For example, class Name implements Comparable<Name> has compareTo(Name), but the erased interface declares compareTo(Object). The compiler generates a compareTo(Object) that casts to Name and calls the real one. Bridges are also generated for covariant return type overrides.

Calling through a raw type with the wrong argument throws ClassCastException from the bridge. Reflection-based frameworks filter with Method.isBridge().

How do you create an instance or an array of T when new T() isn’t allowed?

Pass the type in as a value.

  • Objects: a Supplier<T> (e.g. create(StringBuilder::new)), or a Class<T> with type.getDeclaredConstructor().newInstance() if you need reflection.
  • Arrays: Array.newInstance(type, n) or an IntFunction<T[]> (toArray(String[]::new)).

A supplier is preferred because it avoids reflection and is checked at compile time.

Why are raw types dangerous, and when are you forced to use them?

A raw type (List with no <...>) switches off all generic checks for that variable, so type errors fire late and far from their cause.

Assign a List<String> to a List variable and add(42) only produces an unchecked warning. The ClassCastException shows up later at a read, sometimes in another module.

Use them only where you can’t avoid it: class literals (List.class) and pre-Java 5 libraries. When you must deal with non-type-safe code: enable -Xlint:unchecked, keep @SuppressWarnings to the smallest scope, and wrap collections with Collections.checkedList so the bad add fails on the spot.

Senior

How does Jackson know to deserialize into a List<User> when generics are erased?

Super type token: new TypeReference<List<User>>() {} creates an anonymous subclass, and its generic supertype is still in the .class file.

The supertype TypeReference<List<User>> is stored in the class’s Signature attribute and can be read with getClass().getGenericSuperclass() as a full ParameterizedType. Erasure removes type arguments from objects, not from declarations.

Spring uses the same technique with ParameterizedTypeReference and ResolvableType. Pass List.class instead and Jackson can only build a list of LinkedHashMap.

What is heap pollution? When do you use @SafeVarargs?

Heap pollution is a variable of a parameterized type pointing to an object that isn’t of that type; use @SafeVarargs only when the method neither writes to the varargs array nor leaks it.

Heap pollution comes from raw types or unchecked casts; the failure shows up late, at a compiler-inserted cast. Generic varargs are a common source because the varargs array is created from the erasure (Object[]): returning it causes a ClassCastException in the caller.

@SafeVarargs can only go on static, final and private methods and constructors. Adding it wrongly just hides the warning.

Useful phrases for interviews

  • “Because of type erasure, ArrayList<String> and ArrayList<Integer> share the same runtime class, which is why you can’t do new T() or instanceof List<String>.”
  • “Erasure removes type arguments from objects, but declared signatures are kept in the class file, and that’s what Jackson’s TypeReference relies on.”
  • “When a method needs the type at runtime, I pass it in explicitly, as a Class<T>, a Supplier<T>, or a type reference for nested generics.”
  • “I treat unchecked warnings as potential bugs; if I suppress one, it’s on the smallest scope possible with a comment explaining why it’s safe.”
  • “A sealed interface with generic records gives me an exhaustive switch, so adding a new case breaks the build exactly where it needs to be handled.”
  • “Erasure was the price of backward compatibility: old and new code run together on the same JVM.”
  • “The cast is still in the bytecode; the compiler inserts it and proves it safe.”
  • “That’s a bridge method: a synthetic method the compiler generates to keep overriding working after erasure.”

Notes based on the Hỏi Dân IT Java Core material plus my own research, rewritten in my own words.