Is it possible to extract all members, including private ones, from a class in Java using reflection?

I would like to write, for example

Method[] getMethods(Class<?> c) 

which will do the same as existing

 Class.getMethods() 

but also include private and protected methods. Any ideas how I could do this?

+7
java reflection
source share
3 answers
 public Method[] getMethods(Class<?> c) { List<Method> methods = new ArrayList<Method>(); while (c != Object.class) { methods.addAll(Arrays.asList(c.getDeclaredMethods())); c = c.getSuperclass(); } return methods.toArray(new Method[methods.size()]); } 

Explain:

  • getDeclaredMethods returns all methods declared by a specific class, but not its superclasses
  • c.getSuperclass() returns the immediate superclass of this class
  • so recursive hierarchy, before Object , you get all the methods
  • if you want to include Object methods, then let the condition be while (c != null)
+11
source share

Use Class.getDeclaredMethods() . Note that unlike getMethods() , this will not return the inherited methods - therefore, if you want everything, you will need to restore the type hierarchy.

+3
source share

The Javadoc documentation describes all the details.

+1
source share

All Articles