简体   繁体   中英

Java: Inheriting class can not be converted to super class in method parameter

I have this method with a generic class as parameter:

myMethod(Class myclass){
    Superclass superclass = myclass;
}

then I use the method by passing a child class of the Superclass

myMethod(Mychildclass.class)

Netbeans is giving me a warning that I am using generic "Class". However this works fine. If I change the method's parameter to this more specific

myMethod(Class<Superclass> myclass){
    this.superclass = myclass;
}

then I am getting an error when trying to use my method:

incompatibles types: Class<Mychildclass> cannot be converted to Class<Superclass>

So my question: Why is this not working? How can I make Netbeans happy giving me no warning and no error messages?

Try this instead:

private Class<? extends Superclass> superclass;

void myMethod(Class<? extends Superclass> myclass){
    this.superclass = myclass;
}
  • If you use Class<Superclass> ,
    only Superclass.class is expected.

  • If you use Class<? extends Superclass> Class<? extends Superclass> ,
    Superclass.class or any of its child classes are expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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