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

Viewed 52706

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?

4 Answers
Related