Method method = getClass().getSuperclass().getDeclaredMethod("doSomething");
method.invoke(this);
Run Code Online (Sandbox Code Playgroud)
如果你有更大的层次结构,你可以使用:
Class current = getClass();
Method method = null;
while (current != Object.class) {
try {
method = current.getDeclaredMethod("doSomething");
break;
} catch (NoSuchMethodException ex) {
current = current.getSuperclass();
}
}
// only needed if the two classes are in different packages
method.setAccessible(true);
method.invoke(this);
Run Code Online (Sandbox Code Playgroud)
(上面的示例是针对doSomething没有参数命名的方法.如果您的方法有参数,则必须将它们的类型作为参数添加到getDeclaredMethod(...)方法中)