Gen iOb = new Gen(99);
int x = (Integer) iOb.getob();
Because of erasure, some things work a bit differently than you might think. For example,
consider this short program that creates two objects of the generic Gen class just shown:
class GenTypeDemo {
public static void main(String args[]) {
Gen<Integer> iOb = new Gen<Integer>(99);
Gen<Float> fOb = new Gen<Float>(102.2F);
System.out.println(iOb.getClass().getName());
System.out.println(fOb.getClass().getName());
}
}
The output from this program is shown here:
Gen
Gen
As you can see, the types of both iOb and fOb are Gen, not the Gen<Integer> and
Gen<Float> that you might have expected. Remember, all type parameters are erased
during compilation. At run time, only raw types actually exist.
Bridge Methods
Occasionally, the compiler will need to add a bridge method to a class to handle situations in
which the type erasure of an overriding method in a subclass does not produce the same
erasure as the method in the superclass. In this case, a method is generated that uses the
type erasure of the superclass, and this method calls the method that has the type erasure
specified by the subclass. Of course, bridge methods only occur at the bytecode level, are
not seen by you, and are not available for your use.
Although bridge methods are not something that you will normally need to be concerned
with, it is still instructive to see a situation in which one is generated. Consider the following
program:
// A situation that creates a bridge method.
class Gen<T> {
T ob; // declare an object of type T
// Pass the constructor a reference to
// an object of type T.
Gen(T o) {
ob = o;
}
// Return ob.
T getob() {
return ob;
}
Search WWH :
Custom Search
Previous Page
Java SE 6 Topic Index
Next Page
Java SE 6 Bookmarks
Home