假设我有这个:
class Base {}
class Derived extends Base {}
然后在我的代码中,我可以安全地投射而没有像这样的警告:
public void foo(Base base) {
Derived f = (Derived) base; // fine, no warning
}
这很好.但是如果派生类有更多的类型参数,它就不再起作用了:
class Base {}
class Derived extends Base {}
public void foo(Base base) {
Derived f = (Derived) base; // unchecked warning!
}
这是为什么?有什么明显的东西我在这里不见了吗?
解决方法:
A cast from a type S to a parameterized type (§4.5) T is unchecked
unless at least one of the following conditions holds:
S <: t>
All of the type arguments (§4.5.1) of T are unbounded wildcards
T <: s and has no subtype x other than t where the type arguments of>
X are not contained in the type arguments of T.
鉴于您的类型Base< T>和派生< T,?>分别作为S和T,前两个条件显然不成立.
这留下了第三个条件 – 如果我们能够识别Base< T>的子类型,则不会成立.除了Derived< T,?>其类型参数不包含在Derived< T,?>的类型参数中.如果警告正确,则必须存在这样的子类型,但我无法识别.例如,Derived不起作用,因为它不是Base< T>的子类型.
标签:java,casting,subclass,generics
来源: https://codeday.me/bug/20190520/1141956.html