java 通用类型_java – 转换为泛型类的通用子类型

假设我有这个:

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值