gud*_*dge 7 java generics inheritance
foo以下示例中的方法给出了警告,而bar不是?
public class X {
static class Y {}
static class Z extends Y {}
Y y = new Y();
<T extends Y> T foo() {
return (T) y; // warning - Unchecked cast from X.Y to T
}
Z bar() {
return (Z) y; // compiles fine
}
}
Run Code Online (Sandbox Code Playgroud)
类型 T 在编译时被删除为 Y,这就是泛型在 Java 中的工作方式。因此,当在运行时执行转换时,T 的类型不可用,它只是Y字节码中的 an 。
bar()编译良好,因为所有类型信息都可用(强制转换将失败)。但foo()缺少此类型信息并且不会失败,可能(或肯定在这种情况下)导致方法的类型签名不正确并成为程序中错误的来源。
为了安全地执行此操作,您需要将类本身传递给方法。
<T extends Y> T foo(Class<T> cls) {
return cls.cast(y); //No type warning. Will throw an error when cast fails.
}
Run Code Online (Sandbox Code Playgroud)