我有 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”的方法,如何检查父类?
最佳答案
可以做你所要求的事情(参见答案的末尾),但如果没有充分的理由就这样做,这是糟糕的设计。
如果不需要在运行时确定名称,我会将 Parent
中的方法定义为不执行任何操作,然后调用它;如果子类重写它,那就太好了。
public abstract class Parent {
public void doIt() {
this.specialMethod();
}
public void spacialMethod() {
// Do nothing
}
}
public class Child extends Parent{
@Override
public void spacialMethod() {
// Optionally call super.specialMethod() here
System.out.println("Child special method called");
}
}
public class Child2 extends Parent{
// Empty
}
但是,如果您真的想要通过反射来完成此操作(例如,您需要在运行时定义名称),那么这并不难:
// Not recommended if you can avoid it
public void doIt() {
try {
this.getClass().getMethod("specialMethod").invoke(this);
}
catch (/*...appropriate exception handling...*/) {
}
}
关于java - 调用未知子类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40911701/