当我编译以下Java代码(使用Oracle JDK 1.7.0_25)时:
public class StackOverflowQuestion {
interface Example {
<T extends Example> T init();
}
static class ExampleImpl implements Example {
@Override
public ExampleImpl init() {
return this;
}
}
}
我收到警告:
StackOverflowQuestion.java:11: warning: [unchecked] init()
in ExampleImpl implements <T>init() in Example
public ExampleImpl init() {
^
return type requires unchecked conversion from ExampleImpl to T
where T is a type-variable:
T extends Example declared in method <T>init()
我不明白为什么该类实现时会说“返回类型需要未经检查的转换” Example
,据我所知,这是一个有效的返回类型。
谁能向我解释怎么了?
中的泛型方法Example
应该T
可以在任何可以扩展的类型的地方工作Example
,但是您尝试以ExampleImpl
始终返回a的方式实现它ExampleImpl
。如果ExampleImpl
是唯一实现的类Example
,则可以这样做,但是如果还有其他类可以ClassCastException
在运行时获取。
在下面的例子中,我们实例化一个新的ExampleImpl
,将其转换为基本接口,然后调用泛型方法init()
用T
等于ExampleImpl2
。应该返回一个ExampleImpl2
,但是自从你返回以来this
,它抛出了一个ClassCastException
。这就是为什么您的代码必须生成警告的原因。
public class StackOverflowQuestion {
interface Example {
<T extends Example> T init();
}
static class ExampleImpl implements Example {
@Override
public ExampleImpl init() {
return this;
}
}
static class ExampleImpl2 implements Example {
@Override
public <T extends Example> T init() {
return null;
}
}
public static void main(String[] args) {
ExampleImpl2 e2 = ((Example) new ExampleImpl()).<ExampleImpl2>init();
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句