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

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

Leave a Comment