Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
156 views
in Technique[技术] by (71.8m points)

java - Getting a list of accessible methods for a given class via reflection

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.

Example:

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

For class B I'd like to get:

  • 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 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...