gpt4 book ai didi

java - 这个基本的通用示例真的无法实现吗?

转载 作者:行者123 更新时间:2023-12-02 00:18:27 24 4
gpt4 key购买 nike

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

用户无法获取泛型类 X 的构造函数类型来匹配传递到构造函数 IA 中的对象类型,即使 <X extends IA> .

我不太喜欢所提供的唯一答案,因为如果您必须从 X 更改 M 构造函数类型,那么泛型的全部意义就变得毫无用处。至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 < ASpecificType > 获得的类型安全性,并且编译器会引起您的注意。

以下代码是我能得到的最接近您的代码,同时也有意义:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com