Sub topic 15
Type Erasure: What Happens at Runtime
In earlier chapters, the compiler checked your generic types for you. It stopped you from putting an Integer into a Box<String>. You might expect the running program to know about <String> as well. It does not. This chapter explains why.
What Type Erasure Means
Type erasure is the process the Java compiler uses to remove generic type information after it has checked your code. The compiler uses type arguments like <String> to find mistakes. Then it deletes them. The compiled program, called bytecode, has almost no record of them.
Here are a few terms this chapter uses:
- The compiler (
javac) is the program that turns your.javafiles into.classfiles. - Bytecode is the code inside a
.classfile. - The JVM (Java Virtual Machine) is the program that runs bytecode.
- Runtime means the time when your program is running, as opposed to compile time, when
javacchecks and translates it.
The compiler does three things with generics:
- It checks that every type is used correctly.
- It replaces each type parameter with its erasure. The erasure is the bound of the type parameter, or
Objectif it has no bound. - It adds casts where your code reads a value out, so the types still match.
Why Java Does This
Generics were added in Java 5, in 2004. By then, millions of programs already used plain collections like List and ArrayList. The Java designers wanted old code and new code to work together. New code should be able to pass a List<String> to an old library that expects a plain List.
Erasure made this possible. After erasure, a List<String> and an old List are the same thing in bytecode. The JVM did not need to change. The cost is that the type arguments are gone when the program runs.
Seeing Erasure in Action
This program makes two lists with different type arguments. It then asks each list for its runtime class.
import java.util.ArrayList;
import java.util.List;
public class ErasureDemo {
public static void main(String[] args) {
List<String> strings = new ArrayList<>();
List<Integer> ints = new ArrayList<>();
System.out.println(strings.getClass() == ints.getClass()); // true
System.out.println(strings.getClass().getName()); // java.util.ArrayList
}
}It prints true, then java.util.ArrayList. At runtime there is one class, ArrayList. There is no separate ArrayList<String> class and no ArrayList<Integer> class.
What the Compiler Writes for You
Take the Box<T> class from an earlier chapter. You write this:
public class Box<T> {
private T value;
public Box(T value) {
this.value = value;
}
public T get() {
return value;
}
}After erasure, the bytecode behaves like this plain Java class:
public class Box {
private Object value;
public Box(Object value) {
this.value = value;
}
public Object get() {
return value;
}
}T has no bound, so it becomes Object. Now look at the calling code:
Box<String> box = new Box<>("hi");
String s = box.get();After erasure, it acts like this:
Box box = new Box("hi");
String s = (String) box.get();The compiler added the (String) cast for you. That is the same cast you had to write by hand with raw types in the first chapter. The difference is that the compiler has already proven the cast is safe, so it cannot fail in correct generic code.
Checking the Casts Yourself
You can see the inserted cast with javap, a tool that comes with the JDK. It prints the bytecode of a class. Put this in Main.java, in the same folder as Box.java:
public class Main {
public static void main(String[] args) {
Box<String> box = new Box<>("hi");
String s = box.get();
System.out.println(s);
}
}Then run these commands:
javac Box.java Main.java
javap -c MainIn the output, look for a line like checkcast #.. // class java/lang/String right after the call to Box.get. checkcast is the bytecode instruction for a cast. You did not write it, so the compiler added it.
Erasure with Bounds
If a type parameter has a bound, it erases to that bound instead of Object. For <T extends Number>, every T becomes Number. With several bounds, such as <T extends Number & Comparable<T>>, T erases to the first bound, Number.
This program uses reflection to check. Reflection is a Java feature that lets a program look at its own classes and methods while it runs.
import java.lang.reflect.Method;
public class BoundErasureDemo {
static class PlainBox<T> {
T value;
T get() { return value; }
}
static class NumberBox<T extends Number> {
T value;
T get() { return value; }
}
public static void main(String[] args) throws Exception {
Method plain = PlainBox.class.getDeclaredMethod("get");
Method number = NumberBox.class.getDeclaredMethod("get");
System.out.println(plain.getReturnType().getName()); // java.lang.Object
System.out.println(number.getReturnType().getName()); // java.lang.Number
}
}The table sums up the rule.
| Declaration | Erases to |
|---|---|
| `<T>` | `Object` |
| `<T extends Number>` | `Number` |
| `<T extends Comparable<T>>` | `Comparable` |
| `<T extends Number & Comparable<T>>` | `Number` (the first bound) |
| `List<String>` | `List` |
What Erasure Means for Your Code
Because the type arguments are gone at runtime, some things you might try do not work.
- You cannot ask an object for its type argument.
strings.getClass()givesArrayList, neverArrayList<String>. - You cannot test a generic type at runtime.
obj instanceof List<String>is rejected, because the JVM has no way to check the<String>part.obj instanceof List<?>is allowed. - You cannot overload methods that differ only in type arguments. Both methods below erase to
print(List), so the compiler reports a name clash:
import java.util.List;
public class ClashDemo {
void print(List<String> list) { }
// void print(List<Integer> list) { } // compile error: both methods have the same erasure
}The next chapter covers more limits that come from erasure, such as why new T() is not allowed.
Common Mistakes
- Thinking
List<String>is a separate class. It is not. There is oneListclass, and the compiler does the checking. - Expecting a runtime error from generics. Erasure means the JVM cannot catch a wrong element type when it is added. If unchecked code sneaks in a wrong type, the error shows up later as a
ClassCastExceptionat one of the inserted casts. A later chapter on raw types and heap pollution covers this. - Ignoring compiler warnings. The compiler's checks are your only protection. A warning means it could not fully check something.
Exercise
What does T erase to in class Shelf<T extends CharSequence>, and what does the return type of T get() become in the bytecode?
Show answer
T erases to its bound, CharSequence, so T get() becomes CharSequence get() in the bytecode. Callers using Shelf<String> get an inserted cast to String.
Exercise
A program creates Map<String, Integer> a = new HashMap<>(); and Map<Long, Boolean> b = new HashMap<>();. What does a.getClass() == b.getClass() print, and why?
Show answer
It prints true. Type erasure removes the type arguments, so both objects are instances of the same runtime class, java.util.HashMap.
Exercise
Why does the compiler reject a class that has both void save(List<String> items) and void save(List<Integer> items)?
Show answer
After erasure, both methods have the same signature, save(List). The JVM could not tell them apart, so the compiler reports a name clash.