我有MySuperClass
,MySubClass
和Main
类
MySuperClass.java
public abstract MySuperClass {
String param;
public String getParam() {
return param;
}
}
MySubClass.java
public class MySubClass extends MySuperClass {
}
Main.java
public <T extends MySuperClass> void doWork (Class <T> subClassObject) {
subClassObject.getParam(); // method undefined
}
为什么呢?我指定了T extends MySuperClass
。因此,所有MySuperClass
方法都应该适用于子类。如何从子类对象中调用超类的方法?
答案 0 :(得分:4)
subClassObject
不是MySuperClass
个实例,它是java.lang.Class
个实例。您应该将此参数定义为T
,而不是Class<T>
以获得所需的行为:
public <T extends MySuperClass> void doWork (T subClassObject) {
subClassObject.getParam();
// etc...
}