使用Reflection调用超类方法

Viv*_*vek 9 java

我有2节课,比如A&B:

Class A extends B {
    public void subClassMthd(){
        System.out.println("Hello");
    }
}

Class B {
    public void printHelloWorld {
        System.out.println("Hello");
    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我使用反射来调用类A上的方法.我还想调用类B中的printHelloWorld方法.

我试过用

Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Method superClassmthd = classAInstance.getClass()
    .getSuperclass().getMethod("printHelloWorld", null);
superClassmthd.invoke(classAInstance);
Run Code Online (Sandbox Code Playgroud)

也尝试过

Class clazz = Class.forName("com.test.ClassA");
Object classAInstance= clazz.newInstance();
Class superClazz = Class.forName(classAInstance.getClass().getSuperclass().getName());
Object superclassInstance = superClazz.newInstance();
Method superClassmthd = superclassInstance.getMethod("printHelloWorld", null);
superClassmthd.invoke(superclassInstance );
Run Code Online (Sandbox Code Playgroud)

但它们都不起作用; 他们抛出一个InstantiationException.

我在这做错了什么?

Boh*_*ian 18

试试这个:

Method mthd = classAInstance.getClass().getSuperclass().getDeclaredMethod("XYZ");
mthd.invoke(classAInstance)
Run Code Online (Sandbox Code Playgroud)

的差被使用getDeclaredMethod(),它可以获取的方法所有能见度(public,protected,包/默认和private代替)getMethod(),其只得到方法与public能见度.

  • @ user951793如果超级方法被实例的类覆盖(不是这个问题中的情况),那么当然会调用被覆盖的方法 - 该行为是OOP的核心. (2认同)