我在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」的方法?
爲什麼?爲什麼不在抽象類中定義一個「什麼都不做」的版本,然後調用它,如果子類覆蓋它,它們的版本會被調用? –