使用反射调用静态方法

问题描述 投票:174回答:3

我想调用静态的main方法。我得到了Class类型的对象,但我无法创建该类的实例,也无法调用static方法main

java reflection static
3个回答
262
投票
// 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)


42
投票

来自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)

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;
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.