What javac does
Generics and bridge methods
Erased types, the casts javac inserts, and a synthetic bridge method.
Generic types are erased: in bytecode, List<String> is just List, and get returns Object. javac inserts a checkcast wherever your code relies on the type argument. And when a class implements a generic interface for a specific type, javac generates a bridge method so that calls through the erased interface still reach your code.
The source
// Generics: erased types, casts javac inserts, and a bridge method.
import java.util.ArrayList;
import java.util.List;
public class Bridge implements Comparable<Bridge> {
final int rank;
Bridge(int rank) {
this.rank = rank;
}
@Override
public int compareTo(Bridge other) {
return Integer.compare(rank, other.rank);
}
static String first(List<String> names) {
return names.get(0);
}
static List<String> make() {
return new ArrayList<>();
}
}Compiled by javac 25 with -g and --release 8 to 25. Where releases produce different bytecode, each version is shown.
What to look for
first()callsList.get, thencheckcastString.compareTo(Object)is a synthetic bridge method (ACC_BRIDGE). Callers throughComparableinvoke the erasedcompareTo(Object); the bridge casts its argument to Bridge and calls yourcompareTo(Bridge).new ArrayList<>()is a plainnew ArrayList: type arguments do not exist in the bytecode.- The generic types survive only in Signature attributes, for reflection and for compilers reading the class.
Bridge.class
Bridge(int rank)
javac --release 8 to 25 (the same bytecode for every release)
public int compareTo(Bridge other)
javac --release 8 to 25 (the same bytecode for every release)
static String first(List names)
javac --release 8 to 25 (the same bytecode for every release)
return names.get(0);static List make()
javac --release 8 to 25 (the same bytecode for every release)
public int compareTo(Object) bridge synthetic
javac --release 8 to 25 (the same bytecode for every release)
public class Bridge implements Comparable<Bridge> {