Bridge methods in compiled Java classes

Some Java 1.5 trivia for Monday:

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.

Comments:

Post a Comment:
  • HTML Syntax: NOT allowed
About

toddfast

Search

Archives
« April 2014
SunMonTueWedThuFriSat
  
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
   
       
Today