请考虑以下演示继承和反射的代码:
/*Parent class*/
package basics;
public class Vehicle {
private void parentPrivateMethod() {
System.out.println("This is the child private method");
}
public void print() {
System.out.println("This is a Vehicle method");
}
public void overrideThisMethod() {
System.out.println("Parent method");
}
}
/*Child class*/
package basics;
public class Car extends Vehicle {
private void childPrivateMethod() {
System.out.println("This is the child private method");
}
public String returnCarName() {
return "Manza";
}
@Override
public void overrideThisMethod() {
//super.overrideThisMethod();/*NOTE THIS*/
System.out.println("Child method");
}
}
/*Tester class*/
package basics;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class NewTester {
/**
* @param args
* @throws NoSuchMethodException
* @throws SecurityException
* @throws InvocationTargetException
* @throws IllegalAccessException
* @throws IllegalArgumentException
* @throws InstantiationException
*/
public static void main(String[] args) throws SecurityException,
NoSuchMethodException, IllegalArgumentException,
IllegalAccessException, InvocationTargetException, InstantiationException {
// TODO Auto-generated method stub
Car carInstance = new Car();
/* Normal method invocation */
carInstance.overrideThisMethod();
/* Reflection method invocation */
Method whichMethod = Car.class.getSuperclass().getMethod(
"overrideThisMethod", null);
whichMethod.invoke(carInstance, null);
/* Work-around to call the superclass method */
Method superClassMethod = Car.class.getSuperclass().getMethod(
"overrideThisMethod", null);
superClassMethod.invoke(Car.class.getSuperclass().newInstance(), null);
}
}
输出(带有注释的“注意此”部分)是:
Child method
Child method
Parent method
如果“NOTE THIS”部分未注释,将调用超类方法,并给出输出:
Parent method
Child method
Parent method
Child method
Parent method
当创建 Car 的实例时,Vehicle 的构造函数首先运行。因此,我相信,也创建了一个 Vehicle 实例,Car 实例通过“super”保存其引用。
Question:
如何在不使用 /* Work-around 调用超类方法 */ 的情况下调用“overrideThisMethod”的超类版本?
我在这里忽略了一些东西/在这里做出了错误的假设吗?