是否可以通过Java反射调用超类中的no修饰符方法?
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(...)
method)
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)