Java中的泛型和继承问题

huangapple go评论67阅读模式
英文:

Generics and inheritance issue in Java

问题

请考虑我的代码:

class A {

}

class B extends A {

}

class AWrapper<T extends A> {

}

class BWrapper<T extends B> extends AWrapper<T> {

}

所以,我有 C extends B 等等,以及 CWrapper<T extends C> extends BWrapper<T> 等等。

现在,我以以下方式使用这些类:

class Test {

    private Class<? extends AWrapper<? extends A>> klass; //LINE X

    public Test() {
         this.klass = BWrapper.class; //LINE Z
    }
}

LINE X,我需要设置不同的类 - AWrapper,BWrapper,CWrapper 等等。然而,在 LINE Z 处我遇到了一个错误。有谁可以帮忙解决一下?

英文:

Please, consider my code:

class A {

}

class B extends A {

}

class AWrapper&lt;T extends A&gt; {

}

class BWrapper&lt;T extends B&gt; extends AWrapper&lt;T&gt; {

}

So, I have C extends B etc, and CWrapper&lt;T extends C&gt; extends BWrapper&lt;T&gt; etc.
Now, I use these classes this way:

class Test {

    private Class&lt;? extends AWrapper&lt;? extends A&gt;&gt; klass;//LINE X

    public Test() {
         this.klass = BWrapper.class;//LINE Z
    }
}

At LINE X I need to set different classes - AWrapper, BWrapper, CWrapper etc. However, at LINE Z I get an error. Could anyone help to fix it?

答案1

得分: 1

在我看来,你正在寻找的是:

private Class<? extends AWrapper> klass;

即使 AWrapper 是原始类型。至少这样你可以说你的参数接受“是 AWrapper 的子类型(或自身)的类”。但无论如何,在运行时不会保留泛型信息,所以无论你在那里有什么样的 Class,都将没有其推断的参数。

英文:

imho, what you are looking for is :

private Class&lt;? extends AWrapper&gt; klass;

even if AWrapper is raw. At least this way you could say that your parameter takes "a class that is subtype (or self) of AWrapper". But that should be the thing you care about anyway. Generics are not preserved at runtime, so no matter what Class you have there, it is going to be without its inferred parameters.

huangapple
  • 本文由 发表于 2020年10月21日 05:05:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/64453318.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定