March 4, 2011, 4:33 a.m.
posted by tailcall
As we mentioned earlier, generics are implemented by erasure: when you write code with generics, it compiles in almost exactly the same way as the code you would have written without generics. In the case of a parameterized interface such as Comparable<T>, this may cause additional methods to be inserted by the compiler; these additional methods are called bridges.
Figure shows the Comparable interface and a simplified version of the Integer class in Java before generics. In the nongeneric interface, the compareTo method takes an argument of type Object. In the nongeneric class, there are two compareTo methods. The first is the naïve method you might expect, to compare an integer with another integer. The second compares an integer with an arbitrary object: it casts the object to an integer and calls the first method. The second method is necessary in order to override the compareTo method in the Comparable interface, because overriding occurs only when the method signatures are identical. This second method is called a bridge.
Legacy code for comparable integers
Figure shows what happens when the Comparable interface and the Integer class are generified. In the generic interface, the compareTo method takes an argument of type T. In the generic class, a single compareTo method takes an argument of type Integer. The bridge method is generated automatically by the compiler. Indeed, the compiled version of the code for both examples is essentially identical.
Generic code for comparable integers
You can see the bridge if you apply reflection. Here is code that finds all methods with the name compareTo in the class Integer, using toGenericString to print the generic signature of a method (see Section 7.5).
for (Method m : Integer.class.getMethods()) if (m.getName().equals("compareTo")) System.out.println(m.toGenericString());
Running this code on the generic version of the Integer class produces the following output:
public int Integer.compareTo(Integer) public bridge int Integer.compareTo(java.lang.Object)
This indeed contains two methods, both the declared method that takes an argument of type Integer and the bridge method that takes an argument of type Object. (As of this writing, the Sun JVM prints volatile instead of bridge, because the bit used in Java bytecode to indicate bridge methods is also used to indicate volatile fields; this bug is expected to be fixed in a future release.)