如何使用反射检查方法是否是静态的? [英] How can I check if a method is static using reflection?

查看:29
本文介绍了如何使用反射检查方法是否是静态的?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

推荐答案

使用 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);
}

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

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).

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

Disclaimer: Not tested or even compiled.

注意 Modifier 应该小心使用.表示为整数的标志不是类型安全的.一个常见的错误是在不适用的反射对象类型上测试修饰符标志.可能是在同一位置设置了一个标志来表示一些其他信息.

Note Modifier should 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.

这篇关于如何使用反射检查方法是否是静态的?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆