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表示的标志不是类型安全的.一个常见的错误是在一个它不适用的反射对象类型上测试一个修饰符标志.情况可能是相同位置的标志被设置为表示一些其他信息.
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)
为了充实前面的(正确的)答案,这里有一个完整的代码片段,可以满足您的需求(忽略异常):
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)
| 归档时间: |
|
| 查看次数: |
47576 次 |
| 最近记录: |