Java Reference
In-Depth Information
public Object passThrough(Object o) {
return passThrough((String)o);
}
The compiler would insert calls to this bridge method, rather than calls
to the actual method. Thus, the cast will fail when it should and succeed
otherwise. Because bridge methods are introduced by the compiler, they
will be marked as synthetic.
Bridge methods also fill another role in maintaining backward compat-
ibility. For example, prior to generics the
Comparable
interface's
compareTo
method took an
Object
argument, but now it takes a
T
, whatever that
may be. However, code compiled against non-generified
Comparable
im-
plementations have byte codes to invoke a version of the method that
takes an
Object
. No such version is defined in the source code, but the
compiler generates a
compareTo(Object)
bridge method that casts the ar-
gument to the expected type and invokes the new
compareTo
method.
The use of raw types in code written after generics was added is strongly
discouraged, as they exist only for backward compatibility and may be
removed in a future version of the language.
A.3.2. API Issues
A second compatibility issue concerns the changes to the
API
s them-
selves, within the class libraries. Many, if not all, the generic types in
the class libraries would have been written slightly differently had they
been written from scratch to be generic types. For example, a number of
methods in the collections classes that define a collection of
T
still take
parameters of type
Object
. That was what the old signature specified,
and changing it would break compatibility.
As another example, the reflection method in
java.lang.reflect.Array
to
create a new array is still defined as
public static Object newInstance(Class<?> type, int length)