【发布时间】:2020-04-22 08:16:11
【问题描述】:
这里是代码...
public class Dog {
}
public class Bird {
}
public class Animal< T > {
T field1 = (T) new Bird(); // unchecked cast : Bird to T
public void display() {
System.out.println(field1);
}
}
我期待运行时错误,但它运行良好....
它给了我输出:
com.company.Bird@48140564
在主类中
public static void main(){
Animal<Dog> animal = new Animal();
animal.display(); // I was expecting run time error here
}
【问题讨论】:
-
问题是什么?您面临什么问题?
-
这正是“unchecked cast”警告告诉你的,这个构造的有效性不会在运行时被检查。一些构造可能会失败,而另一些则不会,这使得这很成问题。它可能在远离最初发生堆污染的代码的地方失败。
标签: java class generics field instance