1

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?

10
  • Because not all of your classes share a common super class, I think Class<?> is the best you can do for the type of klass. Commented Oct 20, 2020 at 21:11
  • @markspace Yes, I can do this way, but this case I loose the constraint and I want to keep it. Commented Oct 20, 2020 at 21:14
  • But I'm saying there's no way to keep the constraint. Generics are not covariant. Class<AWrapper> is not a sub type of Class<BWrapper> You can't assign one to the other. Generic aren't meant for this sort of problem. Commented Oct 20, 2020 at 21:16
  • Your BWrapper class already extends AWrapper in "class BWrapper<T extends B> extends AWrapper<T>" Commented Oct 20, 2020 at 21:16
  • Again if you say this.klass = BWrapper.class;//LINE Z, then it means BWrapper.class extends AWrapper, AWrapper (twice) because of line private Class<? extends AWrapper<? extends A>> klass;//LINE X Commented Oct 20, 2020 at 21:18

1 Answer 1

0

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.