Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 898
NellerLess Avatar asked Feb 01 '10 12:02

NellerLess


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

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)
like image 63
Bozho Avatar answered Oct 31 '22 02:10

Bozho


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.

like image 44
Jon Skeet Avatar answered Oct 31 '22 02:10

Jon Skeet