Вы находитесь на странице: 1из 1

GEEK SNACK Venkatesh R S

ThoughtWorks

Nov 18, 2009


Episode 6

Java – Bridges in Generics


In the non-Generics Java world (JDK 1.4 or But hold on second, isn’t Java 5 and above
before) we would have noticed all wrapper classes compilers has got something called ‘type erasure’,
that implement Comparable interface have got two a process where the compiler will remove all the
compareTo methods as shown below: information related to type parameters and type
arguments within a class or method for the sake of
public interface Comparable { being binary compatible with Java
public int compareTo( object obj ); libraries/applications that were created before
} generics?
Doesn’t it mean that the above Java 5 Long
public final class Long extends Number code after compilation should get translated as it is
implements Comparable { in the Java 1.4 versions?
//Override If that’s the case, where does the bridge
public int compareTo( Object obj ) method go which maintains the contract between
{ Long and Comparable interface?
return compareTo( (Long)obj ); Things are suppose to break here. But it actually
} doesn’t why?
public int compareTo( Long That’s where ‘Bridges‘ in Generics comes into
anotherLong) { picture. When the compiler translates the code for
//compare two long objects binary compatibility with older applications, it also
return result; adds the required bridge methods automatically in
} order to sustain the implementation contracts. In
}
this case the contract is between Comparable and
A convenient, compareTo(Long) method which
the class(Long) that is implementing it.
implements the logic for comparison.
The following snippet of reflection code for the
And the compareTo(Object) method from
Long.class should reveal the secret.
Comparable interface acts as a 'bridge' method by
delegating its call to the compareTo(Long long) as final Method[] methods =
shown above. Long.class.getDeclaredMethods();
for (Method method : methods) {
But Post Java 5, with introduction of Generics
and type safety, things have improved and we no System.out.println(method.toString() +
more need the bridge method, compareTo(Object " - IsBrige?:" +
o) and doesn’t have to worry about any method.isBridge());
ClassCastException anymore. The implementation }
of the wrapper class, Long, in Java 5 or above
looks as follows: Output:
.....
public final class Long extends Number public int
implements Comparable<Long> { java.lang.Long.compareTo(java.lang.Lon
g) - IsBrige?:false
@Override public int
public int compareTo(Long other) { java.lang.Long.compareTo(java.lang.Obj
//compare both long objects ect) - IsBrige?:true
return result; ......
}
}