我想调用静态的 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");
如果方法是私有(private)的,请使用 getDeclaredMethod()
而不是 getMethod()
。并在方法对象上调用 setAccessible(true)
。
关于java - 使用反射调用静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2467544/