[TYPES] Java generics unsoundness?
Pete Kirkham
mach.elf at gmail.com
Mon Oct 2 15:39:58 EDT 2006
The section on override-equivalent signatures,
<http://java.sun.com/docs/books/jls/third_edition/html/classes.html#8.4.2>,
indicates the effect is intentional - the erasure of B#compareTo(B)
overrides A#compareTo(Object) as well as Comparable<T>#compareTo(T)
since B#compareTo(B) is override equivalent to A#compareTo(Object) by
erasure.
Since B's method does override A's method, but takes a takes a B, the
object undergoes assignment conversion
<http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.2
>, and being incompatible, a ClassCastException is thrown. This is
achieved via the bridging method.
So I don't believe it's a bug in the compilers, but rather one of
several design features of a Java generics that are intended to help
backwards compatibility. In this case the non-generic version of B
would have been:
class B extends A implements Comparable {
public int compareTo(Object o){
B b = (B)o;
// it's part of the contract of Comparable to throw CCE
if presented
// with the wrong type
return 0;
}
}
Though actually it was common practice prior to 1.5 to add a bridge
method manually so the type-specific method was called when the type
of the argument was know.
Pete
More information about the Types-list
mailing list