DEV Community

Adetayo Akinsanya
Adetayo Akinsanya

Posted on Originally published at unkletayo.dev on

Generics: erasure, raw types, and what the compiler actually does

Generics: erasure, raw types, and what the compiler actually does

A Box<String> and a Box<Integer> are the same class at runtime.

Box<String> stringBox = new Box<>("hello");
Box<Integer> intBox = new Box<>(42);

System.out.println(stringBox.getClass() == intBox.getClass()); // true
System.out.println(stringBox.getClass().getName()); // Box

Enter fullscreen mode Exit fullscreen mode

Both print as Box. Not Box<String> and Box<Integer>. Type parameters do not exist in bytecode. The compiler uses them to check types during compilation, then removes them. This is type erasure.

What erasure means

When the compiler compiles a generic class, it replaces each type parameter with its bound, or with Object if there is no bound.

For Box<T>:

// Source
public class Box<T> {
    private T value;
    public T get() { return value; }
}

// After erasure (what the compiler produces)
public class Box {
    private Object value;
    public Object get() { return value; }
}

Enter fullscreen mode Exit fullscreen mode

For Box<T extends Comparable<T>>:

// Source
public class BoundedBox<T extends Comparable<T>> {
    private T value;
    public T get() { return value; }
    public boolean isGreaterThan(T other) { return value.compareTo(other) > 0; }
}

// After erasure
public class BoundedBox {
    private Comparable value;
    public Comparable get() { return value; }
    public boolean isGreaterThan(Comparable other) { return value.compareTo(other) > 0; }
}

Enter fullscreen mode Exit fullscreen mode

The upper bound becomes the erased type. Comparable, not Object.

At the call site , the compiler inserts casts where needed:

// Source
Box<String> box = new Box<>("hello");
String s = box.get();

// After erasure
Box box = new Box("hello");
String s = (String) box.get(); // compiler inserts cast

Enter fullscreen mode Exit fullscreen mode

The cast is generated for you. As long as you used the generic type correctly, it never fails. If you use a raw type (see below) and put the wrong type in, the cast you never saw fails at runtime.

Bridge methods

Erasure creates a subtlety with inheritance. Suppose you have:

public class StringBox extends Box<String> {
    @Override
    public String get() { return ...; }
}

Enter fullscreen mode Exit fullscreen mode

After erasure, Box.get() returns Object. StringBox.get() returns String. These are different method signatures, so StringBox.get() is not technically overriding Box.get() in bytecode.

The compiler generates a bridge method to fix this:

// Generated by compiler, not in source
public Object get() {
    return (Object) this.get(); // calls the String version
}

Enter fullscreen mode Exit fullscreen mode

The bridge method has the erased signature from the parent class and delegates to the covariant override. This keeps polymorphism working correctly through erased types. You will occasionally see bridge methods in stack traces or when inspecting a class with reflection; they are always labeled synthetic.

Restrictions that follow from erasure

You cannot use instanceof with a type parameter. At runtime, T is gone. x instanceof T has nothing to check against.

public <T> boolean isInstance(Object x) {
    return x instanceof T; // compile error
}

Enter fullscreen mode Exit fullscreen mode

The workaround is to pass a Class<T> parameter:

public <T> boolean isInstance(Object x, Class<T> type) {
    return type.isInstance(x);
}

Enter fullscreen mode Exit fullscreen mode

You cannot create instances or arrays of a type parameter.

T value = new T(); // compile error
T[] array = new T[10]; // compile error

Enter fullscreen mode Exit fullscreen mode

For instance creation, the workaround is to pass a Supplier<T> or Class<T>. For arrays, use Object[] and cast, or use a List<T> instead.

You cannot catch a generic exception type. catch (T e) is a compile error because exception handling uses runtime types.

Static fields cannot have a generic type. static T value is a compile error. Static members belong to the class itself, not to any parameterization of it, and there is only one class at runtime.

Raw types

A raw type is a generic class used without its type argument:

Box rawBox = new Box("hello"); // raw type
Object value = rawBox.get(); // returns Object, no type info

Enter fullscreen mode Exit fullscreen mode

Raw types exist for backward compatibility with pre-generics Java (before Java 5). The compiler treats a raw type as if its type parameters were all Object. It allows the use but emits an unchecked warning to signal that type safety is no longer guaranteed.

Box rawBox = new Box(42);
String s = (String) rawBox.get(); // compiles with warning, ClassCastException at runtime

Enter fullscreen mode Exit fullscreen mode

The warning is "Unchecked or unsafe operation". It means you have stepped outside the generic type system and the compiler can no longer protect you.

Do not use raw types in new code. They were acceptable in Java 1.4 code that predates generics; in modern Java, every use of a generic type should provide its type argument. When working with legacy APIs that return raw types, cast to the parameterized type and understand that you are assuming the correctness the compiler cannot verify.

Unchecked warnings can be suppressed with @SuppressWarnings("unchecked"), but do so only when you have verified the assumption by other means and can explain why it holds.

Reifiable types

A type is reifiable if its full type information is available at runtime: String, int[], List (raw), List<?>. A List<String> is not reifiable because the String part is erased.

This matters for arrays. Java allows arrays of reifiable types (String[], Object[], List<?>[]) but not arrays of non-reifiable parameterized types (List<String>[]). The compiler rejects the latter because it cannot enforce type safety through the combination of array covariance and generic erasure.

If you need a collection of a parameterized type, use List<List<String>> instead of List<String>[].

Heap pollution

Heap pollution occurs when a variable of a parameterized type refers to an object that is not of that parameterized type. This is the runtime consequence of using raw types or unchecked casts incorrectly:

List rawList = new ArrayList<Integer>();
rawList.add("not an integer"); // no compile error on raw list

List<Integer> typedList = rawList; // unchecked warning
Integer value = typedList.get(0); // ClassCastException here

Enter fullscreen mode Exit fullscreen mode

The ClassCastException appears at typedList.get(0), not at the line where the string was added. The mismatch happened earlier, but erasure hid it until a cast was needed. Heap pollution makes bugs hard to trace because the exception occurs far from the cause.

The @SafeVarargs annotation (Java 7+) suppresses unchecked warnings on varargs methods that use a generic type, when the author has verified that the method does not cause heap pollution. It is a promise to the compiler, not a guarantee.

Prediction exercise

public static <T> T[] toArray(List<T> list) {
    T[] array = (T[]) new Object[list.size()];
    for (int i = 0; i < list.size(); i++) {
        array[i] = list.get(i);
    }
    return array;
}

String[] result = toArray(List.of("a", "b", "c"));

Enter fullscreen mode Exit fullscreen mode

Does this compile? Does it run without error? What exception, if any, is thrown and on which line? Then: why does this fail when the equivalent with Object[] would not? The next article moves to functional interfaces and lambdas: how Java represents a behavior as a value. Functional interfaces and lambdas continues from here.

Top comments (0)