超类中使用默认修饰符的Java反射访问方法

Vip*_*pin 5 java reflection

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

Boz*_*zho 7

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


Rus*_*ard 1

是的。在调用 Method 对象之前,您可能需要对其调用 setAccessible(true)。