【发布时间】:2012-01-23 04:18:47
【问题描述】:
我在泛型方法中测试了一些有界参数的东西,我发现了一些奇怪的行为。
如果有人能解释以下代码 sn-p 中的两个错误,那就太好了。
假设有两个类Class1 和Class2 都从BaseClass 扩展而来。 Class2 实现了一个接口。
在Class1 中,我有一个方法可以通过以下方式返回Class2 的实例:
public class Class2 extends BaseClass implements Interface {
@Override
public void method() {
System.out.println("test"); //$NON-NLS-1$
}
}
public class Class1 extends BaseClass {
public <T extends BaseClass & Interface> T getTwo() {
return new Class2();
// Error: Type mismatch: cannot convert from Class2 to T
}
public static void main(String[] args) {
Interface two = new Class1().getTwo();
// Error: Bound mismatch: The generic method getTwo() of type Class1 is
// not applicable for the arguments (). The inferred type Interface is
// not a valid substitute for the bounded parameter <T extends BaseClass
// & Interface>
System.out.println(two);
}
}
【问题讨论】:
-
这似乎是对泛型的滥用。实际上
getTwo必须只有Class2或BaseClass或Interface的返回类型。如果T只为一种方法定义,那么编译器就无法知道在new Class1().getTwo()行中哪个类完全替代了T。只有getTwo有这种类型的输入参数才有可能。