Java 如何使用反射检查方法是否是静态的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/287645/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 12:36:12  来源:igfitidea点击:

How can I check if a method is static using reflection?

javareflection

提问by Telcontar

I want to discover at run-time ONLY the static Methods of a class, how can I do this? Or, how to differentiate between static and non-static methods.

我只想在运行时发现类的静态方法,我该怎么做?或者,如何区分静态和非静态方法。

采纳答案by Tom Hawtin - tackline

Use Modifier.isStatic(method.getModifiers()).

使用Modifier.isStatic(method.getModifiers()).

/**
 * Returns the public static methods of a class or interface,
 *   including those declared in super classes and interfaces.
 */
public static List<Method> getStaticMethods(Class<?> clazz) {
    List<Method> methods = new ArrayList<Method>();
    for (Method method : clazz.getMethods()) {
        if (Modifier.isStatic(method.getModifiers())) {
            methods.add(method);
        }
    }
    return Collections.unmodifiableList(methods);
}

Note: This method is actually dangerous from a security standpoint. Class.getMethods "bypass[es] SecurityManager checks depending on the immediate caller's class loader" (see section 6 of the Java secure coding guidelines).

注意:从安全的角度来看,这种方法实际上是危险的。Class.getMethods “根据直接调用者的类加载器绕过 [es] SecurityManager 检查”(请参阅​​ Java 安全编码指南的第 6 节)。

Disclaimer: Not tested or even compiled.

免责声明:未经测试甚至编译。

Note Modifiershould be used with care. Flags represented as ints are not type safe. A common mistake is to test a modifier flag on a type of reflection object that it does not apply to. It may be the case that a flag in the same position is set to denote some other information.

注意Modifier应谨慎使用。表示为整数的标志不是类型安全的。一个常见的错误是在不适用的反射对象类型上测试修饰符标志。可能会出现在相同位置设置标志以表示某些其他信息的情况。

回答by Daniel Spiewak

To flesh out the previous (correct) answer, here is a full code snippet which does what you want (exceptions ignored):

为了充实之前的(正确)答案,这里有一个完整的代码片段,它可以满足您的需求(忽略异常):

public Method[] getStatics(Class<?> c) {
    Method[] all = c.getDeclaredMethods()
    List<Method> back = new ArrayList<Method>();

    for (Method m : all) {
        if (Modifier.isStatic(m.getModifiers())) {
            back.add(m);
        }
    }

    return back.toArray(new Method[back.size()]);
}

回答by bruno conde

You can get the static methods like this:

你可以得到这样的静态方法:

for (Method m : MyClass.class.getMethods()) {
   if (Modifier.isStatic(m.getModifiers()))
      System.out.println("Static Method: " + m.getName());
}