Video in progress
What is a bridge method, and when does the compiler create one?
It's a synthetic method that the compiler adds on its own when you inherit from a generic type or narrow a return type. It routes the post-erasure signature to your method, so polymorphism doesn't break.
📖 Answer
An example:
class NameComparator implements Comparator<String> {
public int compare(String a, String b) { return a.compareTo(b); }
}
After erasure, the Comparator interface has compare(Object, Object), while your class has only compare(String, String). They don't override each other. So the compiler adds a hidden method to the class:
// synthetic, in the bytecode
public int compare(Object a, Object b) {
return compare((String) a, (String) b);
}
Where you run into this in practice:
- if you run
javap -p NameComparator.class, you'll see twocomparemethods; - with reflection,
getDeclaredMethods()returns the bridge too, so you have to filter withmethod.isBridge(). This is a classic source of bugs in libraries that scan annotations; - if an argument of the wrong type arrives through a raw type, the
ClassCastExceptioncomes not in your code but inside the bridge, so the stack trace points at a line where you think "there's no such line in my code".
A covariant return type (User clone() instead of Object clone()) creates a bridge too.
Sign up to mark studied questions and save your progress.