Ste*_*ven 185 java reflection static
我想调用main静态的方法.我得到了类型的对象Class,但我无法创建该类的实例,也无法调用该static方法main.
Ade*_*ari 272
// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");
Run Code Online (Sandbox Code Playgroud)
如果该方法是私人使用getDeclaredMethod()而不是getMethod().并调用setAccessible(true)方法对象.
atk*_*atk 44
来自Method.invoke()的Javadoc:
如果底层方法是静态的,则忽略指定的obj参数.它可能是null.
当你发生什么事
Class klass = ...; Method m = klass.getDeclaredMethod(methodName, paramtypes); m.invoke(null, args)
小智 10
String methodName= "...";
String[] args = {};
Method[] methods = clazz.getMethods();
for (Method m : methods) {
if (methodName.equals(m.getName())) {
// for static methods we can use null as instance of class
m.invoke(null, new Object[] {args});
break;
}
}
Run Code Online (Sandbox Code Playgroud)
public class Add {
static int add(int a, int b){
return (a+b);
}
}
Run Code Online (Sandbox Code Playgroud)
在上面的示例中,“add”是一个静态方法,它接受两个整数作为参数。
以下代码片段用于使用输入 1 和 2 调用“add”方法。
Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);
Run Code Online (Sandbox Code Playgroud)
参考链接。