views:

93

answers:

3

I'd like to be able to write, for example

Method[] getMethods(Class<?> c)

which would do the same thing as the existing

Class.getMethods()

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

+3  A: 

Use Class.getDeclaredMethods() instead. Note that unlike getMethods(), this won't return inherited methods - so if you want everything, you'll need to recurse up the type hierarchy.

Jon Skeet
+9  A: 
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()]);
}

To explain:

  • getDeclaredMethods returns all methods that are declared by a certain class, but not its superclasses
  • c.getSuperclass() returns the immediate superclass of the given class
  • thus, recursing up the hierarchy, until Object, you get all methods
  • in case you want to include the methods of Object, then let the condition be while (c != null)
Bozho
Good code. Why do all the way up just below the `Object` class?
fastcodejava
Because generally one wants only _his_ hierarchy. In my updated answer I included a bullet indicating how to include the Object methods as well
Bozho
+1  A: 

Javadoc documentation describes all the details.

fastcodejava