简体   繁体   English

是否可以使用反射从Java中的类中检索所有成员(包括private)?

[英]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 getDeclaredMethods返回由某个类声明的所有方法, 但不返回其超类
  • c.getSuperclass() returns the immediate superclass of the given class c.getSuperclass()返回给定类的直接超类
  • thus, recursing up the hierarchy, until Object , you get all methods 因此,递归层次结构,直到Object ,您获得所有方法
  • in case you want to include the methods of Object , then let the condition be while (c != null) 如果你想包含Object的方法,那么让条件为while (c != null)

Use Class.getDeclaredMethods() instead. 请改用Class.getDeclaredMethods() Note that unlike getMethods() , this won't return inherited methods - so if you want everything, you'll need to recurse up the type hierarchy. 请注意,与getMethods()不同,这不会返回继承的方法 - 因此,如果您想要所有内容,则需要递归类型层次结构。

Javadoc文档描述了所有细节。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM