简体   繁体   English

Java中的泛型和继承问题

[英]Generics and inheritance issue in Java

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:所以,我有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
    }
}

At LINE X I need to set different classes - AWrapper, BWrapper, CWrapper etc. However, at LINE Z I get an error.LINE X我需要设置不同的类 - AWrapper、BWrapper、CWrapper 等。但是,在LINE Z我得到一个错误。 Could anyone help to fix it?任何人都可以帮助修复它吗?

imho, what you are looking for is :恕我直言,您正在寻找的是:

private Class<? extends AWrapper> klass;

even if AWrapper is raw.即使AWrapper是原始的。 At least this way you could say that your parameter takes "a class that is subtype (or self) of AWrapper ".至少通过这种方式,您可以说您的参数采用“一个属于AWrapper子类型(或自身)的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.泛型不会在运行时保留,因此无论您在那里拥有什么Class ,它都将没有其推断参数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM