问题

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


#1 热门回答(160 赞)

UseModifier.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);
}

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

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

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


#2 热门回答(13 赞)

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

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

#3 热门回答(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()]);
}

原文链接