昨天看到此帖子:How I instantiate? Include code

即使<X extends IA>,用户也无法获得通用类X的构造函数类型以匹配传递给构造函数IA的对象的类型。

我真的不喜欢提供的唯一答案,因为如果必须将M构造函数类型从X更改为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包括“扩展”在内的所有地方都包括在内

最佳答案

您必须执行以下操作:

//Testing code in a different class
public <X extends IA<X>> void check() {
    IA<X> a = new A<X>();
    W<subtypeofIA(IA works as well)> s = new M<subtypeofIA(IA works as well)>(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
}


关于警告,我认为它们是不言自明的,它们可以概括为:当您想要使用泛型参数化类型时,必须将泛型参数实例化为具体类型。引入了通用参数以使代码通用,也可以增强类型安全性。使用IA意味着您可以通过说出:IA 来放弃类型安全性,编译器会引起您的注意。

以下代码是我能找到的最接近您的代码,同时又可以理解的代码:

interface IA<X extends IA<X>>{}

class A<X extends IA<X>> implements IA<X>{}

class W<X extends IA<X>>{}

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>(null); //Doesn't compile because IA<X> is not the same as 'X', even though <X extends IA>
    W<X> ss = new M(a);    //Compiles, but with suppressed warnings

    X aa = new A<X>();  //this is completely illegal
    W<X> sss = new M<X>(aa); //compiles
}

关于java - 这个基本的通用示例真的无法实现吗?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11470800/

10-09 03:54