使用反射调用静态方法

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)

  • 为什么不使用正确名称的getMethod而不是循环遍历所有方法? (11认同)
  • 有时,通过名称循环和查找方法要比使用getMethod容易得多,因为getMethod(或getDeclaredMethod)要求您非常详细地计算出参数类型.这取决于微效率是否重要 - Java迭代非常快,所以除非你在某个内循环中调用方法数百万次,否则迭代将足够快 (11认同)
  • 但是,重载方法会有不好的时间. (4认同)
  • 此外,在更现实的情况下,即使您要使用反射多次调用它,您也可能只会找到一次该方法.因此,找到它时额外的开销是无关紧要的. (2认同)

Har*_*hna 6

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)

参考链接