超类中使用默认修饰符的Java反射访问方法 [英] Java reflection accessing method with default modifier in the super class

查看:148
本文介绍了超类中使用默认修饰符的Java反射访问方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以通过Java反射调用超类中的no修饰符方法?

Is it possible to invoke the no modifier method in a superclass through Java reflection?

推荐答案

Method method = getClass().getSuperclass().getDeclaredMethod("doSomething");
method.invoke(this);

如果你有更大的层次结构,你可以使用:

if you have a bigger hierarchy, you can use:

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(...)方法)

(the above examples are for a method named doSomething with no arguments. If your method has arguments, you have to add their types as arguments to the getDeclaredMethod(...) method)

这篇关于超类中使用默认修饰符的Java反射访问方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆