我在Java中有抽象类。我想用反射调用他的子类(如果存在的话)的具体方法。未知子类的调用方法
public abstract class Parent {
public void doIt(String functionName) {
if (the caller class have method called as functionName parameter) {
call it
}
}
}
public class Child extends Parent{
public void spacialMethod() {
System.out.println("Child special method called");
}
}
public class Child2 extends Parent{
// Empty
}
所以,如果我将运行该代码:
Child child = new Child();
child.doIt("spacialMethod"); // Will print the text
Child2 child2 = new Child2();
child2.doIt("spacialMethod"); // Nothing will happened
我怎样才能在父类检查当前的子类都被称为“specialMethod”的方法?
为什么?为什么不在抽象类中定义一个“什么都不做”的版本,然后调用它,如果子类覆盖它,它们的版本会被调用? –