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

这篇博客探讨了如何在Java中使用反射检查方法是否是静态的。提供了多个示例代码片段,包括使用Modifier.isStatic方法来过滤静态方法。同时,警告了使用反射的安全风险和类型安全问题。
摘要由CSDN通过智能技术生成

问题

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

#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 getStaticMethods(Class> clazz) {

List methods = new ArrayList();

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 back = new ArrayList();

for (Method m : all) {

if (Modifier.isStatic(m.getModifiers())) {

back.add(m);

}

}

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

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值