Content #
JVM 虚拟机的角度来看,并不存在 Generic Type。定义新的 Generic Type,会自动生成对应的 Raw Type。
Raw Type 的名字和 Generic Type 的名字相同,并把 Type Variable 替换成 Bounds List 中的第一个 Type(没有显式声明 Bounding Type 的话就使用 Object )。使用过程中碰到 Generic Type,编译器会先调用 Raw Type 对应的方法,然后添加强制类型转换。
Generic Type 在 Java 中只是用编译器自动添加的强制类型转换代替了程序员的强制类型转换。
考虑下面的 Generic Type:
public class Interval<T extends Comparable & Serializable> implements Serializable
{
public Interval(T first, T second)
{
if (first.compareTo(second) <= 0) { lower = first; upper = second; }
else { lower = second; upper = first; }
}
. . .
private T lower;
private T upper;
}
由 Interval 生成的 Raw Type 会是下面这个样子:
public class Interval implements Serializable
{
public Interval(Comparable first, Comparable second) { . . . }
. . .
private Comparable lower;
private Comparable upper;
}
如果 Interval 写成下面这样:
public class Interval<T extends Serializable & Comparable>
那么所有出现 Comparable 的地方会替换成 Serializable,在需要使用 Comparable 接口时再作强制类型转换。
因此,像 Serializable 这样只作标记用的接口,最好不要出现在 Bounds List 的第一个位置。