强制转换为通用类型(T)会产生“未经检查的强制转换"警告
我在这里遇到了一个关于列表的泛型有界类型的小问题.请帮忙!
I got a small problem here regarding generics bounded type with lists. Please help out!
Model.java
Model.java
public class Model {
}
ClassA.java
ClassA.java
public class ClassA<T extends Model> {
private List<T> models;
public ClassA() {
models.add((T) new Model());
}
}
这使我在此行上得到了从Model到T的未经检查的强制转换警告:
It gives me an unchecked cast from Model to T warning on this line:
models.add((T) new Model());
我知道我收到此警告是因为我可以安全地将所有内容从子类强制转换为超类,但反之则不行.
I understand I'm getting this warning because all I can safely cast from a sub class into a super class but not the other way round.
有什么办法可以解决这个问题,或者我可以安全地抑制警告吗?
Is there any way to get over this problem or can I just safely supress the warning?
您无法做您想做的事情.
You can't do what you're trying to do.
由于 T 是 Model 的子类:
- 每个 T 是一个 Model
- ,但不是每个 Model 都是一个 T .
- every T is a Model
- but not every Model is a T.
具体是:
如果通过调用 new Model()构造新模型,则该实例完全是Model,而不是任何子类的实例.
If you construct a new Model by calling new Model(), the instance is exactly a Model and not an instance of any subclass.
在子类扩展超类的地方,您永远无法成功做到这一点:
Where Subclass extends Superclass, you can never successfully do this:
(Subclass) new Superclass();
因此,您无法成功将新模型投射到T的实例.
Because of this, you can not successfully cast a new Model to an instance of T.
编译器只会向您发出警告,您可以忽略或隐藏它,但是在运行程序并调用 add()时,您会收到 ClassCastException . >方法.
The compiler will just give you a warning which you can either ignore or suppress, but you'll get a ClassCastException when you run your program and call the add() method.