开发者

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?


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)


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.


Javadoc documentation describes all the details.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜