是否可以通过Java反射调用父类(super class)中的无修饰符方法?
最佳答案
Method method = getClass().getSuperclass().getDeclaredMethod("doSomething");
method.invoke(this);
如果你有更大的层次结构,你可以使用:
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);
(以上示例是针对名为 doSomething
且没有参数的方法。如果您的方法有参数,则必须将它们的类型作为参数添加到 getDeclaredMethod(...)
方法)
关于父类(super class)中带有default修饰符的Java反射访问方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2100412/