昨天看到这个帖子:我如何实例化?包含代码
用户无法获取泛型类的构造函数类型 X 以匹配传递给构造函数 IA 的对象类型,即使<X extends IA>
.
我真的不喜欢提供的唯一答案,因为如果您必须将 M 构造函数类型从X
to更改,它会使泛型的全部意义变得无用IA<X>
。当然这就是为什么泛型类型M
为<X extends IA>
??
对于这个基本示例,真的没有办法使用泛型(没有任何抑制的警告)吗?
public interface IA<X extends IA<X>>{}
public class A<X extends IA<X>> implements IA<X>{}
public class W<X extends IA<X>>{}
public class M<X extends IA<X>> extends W<X>{
X anx;
public M(X x){} //Type X here is not compatibile with IA in the test code
}
//Testing code in a different class
public <X extends IA<X>> void check() {
IA<X> a = new A<X>();
W<X> s = new M<X>(a); //Doesn't compile because IA<X> is not the same as 'X', even though <X extends IA>
W<X> s = new M(a); //Compiles, but with suppressed warnings
X a = new A<X>(); //Doesnt compiler (ignoring dupicate 'a' variable)
W<X> s = new M<X>(a); compiles
}
编辑以在任何地方包括 IA,包括“扩展”