[英]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". Netbeans向我警告我正在使用通用的“类”。 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? 如何使Netbeans高兴,不给我任何警告,也没有错误消息?
Try this instead: 尝试以下方法:
private Class<? extends Superclass> superclass;
void myMethod(Class<? extends Superclass> myclass){
this.superclass = myclass;
}
If you use Class<Superclass>
, 如果您使用Class<Superclass>
,
only Superclass.class
is expected. 仅Superclass.class
是预期的。
If you use Class<? extends Superclass>
如果您使用Class<? extends Superclass>
Class<? extends Superclass>
, Class<? extends Superclass>
,
Superclass.class
or any of its child classes are expected. Superclass.class
或其任何子类是预期的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.