通过反射获取给定类的可访问方法列表

Chs*_*y76 28 java reflection

有没有办法获得给定类可以访问(不一定是公共)的方法列表?有问题的代码将在一个完全不同的类中.

例:

public class A {
  public void methodA1();
  protected void methodA2();
  void methodA3();
  private void methodA4();
}

public class B extends A {
  public void methodB1();
  protected void methodB2();
  private void methodB3();
}
Run Code Online (Sandbox Code Playgroud)

上课B我想得到:

  • 所有自己的方法
  • methodA1methodA2从类A
  • methodA3当且仅当类B与包在同一个包中时A

methodA4永远不应该包括在结果中,因为它不能被类访问B.为了再次澄清,需要查找和返回上述方法的代码将在完全不同的类/包中.

现在,Class.getMethods()只返回公共方法,因此不会做我想要的; Class.getDeclaredMethods()只返回当前类的方法.虽然我当然可以使用后者并且可以手动检查类层次结构来检查可见性规则,但是如果有更好的解决方案,我宁愿不这样做.我在这里错过了一些明显的东西吗?

cle*_*tus 36

用于Class.getDeclaredMethods()从类或接口获取所有方法(私有或其他)的列表.

Class c = ob.getClass();
for (Method method : c.getDeclaredMethods()) {
  if (method.getAnnotation(PostConstruct.class) != null) {
    System.out.println(method.getName());
  }
}
Run Code Online (Sandbox Code Playgroud)

注意:这不包括继承的方法.使用Class.getMethods()了点.它将返回所有公共方法(继承或不继承).

要对类可以访问的所有内容(包括继承的方法)进行全面的列表,您需要遍历它扩展的类树.所以:

Class c = ob.getClass();
for (Class c = ob.getClass(); c != null; c = c.getSuperclass()) {
  for (Method method : c.getDeclaredMethods()) {
    if (method.getAnnotation(PostConstruct.class) != null) {
      System.out.println(c.getName() + "." + method.getName());
    }
  }
}
Run Code Online (Sandbox Code Playgroud)


Joh*_*ing 6

正如cletus和PSpeed已经回答的那样 - 你需要遍历类的继承树.

这是我这样做的方式,但是没有处理包私有方法:

public static Method[] getAccessibleMethods(Class clazz) {
   List<Method> result = new ArrayList<Method>();

   while (clazz != null) {
      for (Method method : clazz.getDeclaredMethods()) {
         int modifiers = method.getModifiers();
         if (Modifier.isPublic(modifiers) || Modifier.isProtected(modifiers)) {
            result.add(method);
         }
      }
      clazz = clazz.getSuperclass();
   }

   return result.toArray(new Method[result.size()]);
}
Run Code Online (Sandbox Code Playgroud)

我在向后兼容性检查器中使用它,我知道可能受影响的类无论如何都不会在同一个包中.