Bridge methods in compiled Java classes
By toddfast on Apr 11, 2005
Q: What are bridge methods?
A: Bridge methods are mentioned in the JavaDoc for
java.lang.reflect.Method, but there is no mention of them in the second edition of the JLS. I hunted around a little bit and found this excellent description. In a nutshell, bridge methods are a side effect of type erasure as the compiler compiles generic types. Just like the automatic addition of null constructors to classes that don't declare any constructors, bridge methods are some of the hidden magic the Java compiler performs on our behalf.
In the example given in the article, there are two
compareTo() methods in the compiled class. The bridge method is the one with the parameter type of
Object. When using reflection, you may want to know whether a
Method instance you are looking at is (or is not) a bridge method. Thankfully, the
Method class now includes a method called
isBridge() to allow you to determine if the method is a bridge method or not. Just remember that in subclasses/implementations of a generic type like
Comparator, the bridge method is generally the one that you want to find instead of the original method! That is, the bridge method is the one that satisifies the contract of the supertype; the original method is just another arbitrary method as far as the compiler is concerned.