英文:
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<T extends A> {
}
class BWrapper<T extends B> extends AWrapper<T> {
}
So, I have C extends B
etc, and CWrapper<T extends C> extends BWrapper<T>
etc.
Now, I use these classes this way:
class Test {
private Class<? extends AWrapper<? extends A>> 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<? extends AWrapper> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论