【发布时间】:2014-07-03 01:11:26
【问题描述】:
当使用具有具体类型(满足该泛型类型)的方法实现具有泛型类型的接口方法时,会出现未经检查的覆盖警告。
这是一个示例代码:
interface SomeType{}
class Impl1 implements SomeType{}
interface SomeInterface{
<T extends SomeType> T justDoIt();
}
class SomeInterfaceImpl implements SomeInterface{
public Impl1 /*here i get the warning*/ justDoIt(){
return null;
}
}
警告说:返回类型需要未经检查的转换......谁能解释一下。我知道类型擦除,但这在编译时可以验证,没有未经检查的强制转换。
重要的问题。实现这一点的正确方法是什么?鉴于我希望能够实现 SomeInterface 但提供具体类型的编译时类型安全(不使用 SomeType 而是使用具体的 SomeType 后代)?
更新:这就是我想做的事
interface SomeType{
}
class Impl1 implements SomeType{
}
interface SomeInterface{
SomeType convert(String param);
String convert(SomeType param);
}
class SomeInterfaceImpl implements SomeInterface{
public Impl1 justDoIt(){
return null;
}
@Override
public Impl1 convert(String param) {
return null;
}
@Override
public String convert(Impl1/*compile error right here*/ param) {
return null;
}
}
我希望现在我的初衷很清楚。我需要为转换器提供通用接口...
【问题讨论】:
-
I know about type erasure but this is verifyable at compile time that there is no unchecked cast.错误。如果有人写instance.<Impl2> justDoIt()怎么办? -
为什么需要方法类型参数呢?为什么不能只有一个方法
SomeType justDoIt()? -
@SLaks 请查看更新后的问题。