通过反射获取给定类的可访问方法列表 [英] Getting a list of accessible methods for a given class via reflection

查看:130
本文介绍了通过反射获取给定类的可访问方法列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Is there a way to get a list of methods that would be accessible (not necessarily public) by a given class? The code in question will be in a completely different class.

示例:

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();
}

对于班级 B 我想得到:


  • 所有自己的方法

  • methodA1 methodA2 来自班级 A

  • methodA3 当且仅当类 B A

  • all of its own methods
  • methodA1 and methodA2 from class A
  • methodA3 if and only if class B is in the same package as A

methodA4 不应该包含在结果中,因为它无法访问上课 B 。为了再次澄清,需要查找并返回上述方法的代码将在完全不同的类/包中。

methodA4 should never be included in results because it's inaccessible to class B. To clarify once again, code that needs to find and return the above methods will be in a completely different class / package.

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

Now, Class.getMethods() only returns public methods and thus won't do what I want; Class.getDeclaredMethods() only returns methods for current class. While I can certainly use the latter and walk the class hierarchy up checking the visibility rules manually, I'd rather not if there's a better solution. Am I missing something glaringly obvious here?

推荐答案

使用 Class.getDeclaredMethods() 获取所有方法的列表(私有或来自类或接口。

Use Class.getDeclaredMethods() to get a list of all methods (private or otherwise) from the class or interface.

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

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

Note: this excludes inherited methods. Use Class.getMethods() for that. It will return all public methods (inherited or not).

执行类可以访问的所有内容的完整列表(包括继承的方法) ,您将需要遍历它扩展的类树。所以:

To do a comprehensive list of everything a class can access (including inherited methods), you will need to traverse the tree of classes it extends. So:

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());
    }
  }
}

这篇关于通过反射获取给定类的可访问方法列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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