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

Tel*_*tar 102 java reflection

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

Tom*_*ine 177

使用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);
}
Run Code Online (Sandbox Code Playgroud)

注意:从安全角度来看,此方法实际上很危险.Class.getMethods"绕过[es] SecurityManager检查,具体取决于直接调用者的类加载器"(参见Java安全编码指南的第6节).

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

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

  • 是的,谢谢.虽然我声称这个名字是一个错误的设计.修饰符不表示修饰符.但是整个班级都是一个错误的设计.也可能是反思. (4认同)

bru*_*nde 13

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

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


Dan*_*wak 5

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

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()]);
}
Run Code Online (Sandbox Code Playgroud)