我有一个MySuperClassMySubClassMain

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方法都应适用于该子类。如何从子类对象调用父类(super class)的方法?

最佳答案

subClassObject不是MySuperClass实例,它是 java.lang.Class 实例。您应该将此参数定义为T,而不是Class<T>以获得所需的行为:

public <T extends MySuperClass> void doWork (T subClassObject) {
   subClassObject.getParam();
   // etc...
}

09-10 02:54