我想调用静态的main
方法。我得到了Class
类型的对象,但我无法创建该类的实例,也无法调用static
方法main
。
// 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");
如果该方法是私人使用getDeclaredMethod()
而不是getMethod()
。并在方法对象上调用setAccessible(true)
。
来自Method.invoke()的Javadoc:
If the underlying method is static, then the specified obj argument is ignored. It may be null.
当你发生什么事
Class klass = ...; Method m = klass.getDeclaredMethod(methodName, paramtypes); m.invoke(null, args)
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;
}
}