Java 使用反射调用静态方法

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2467544/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:05:35  来源:igfitidea点击:

Invoking a static method using reflection

javareflectionstatic

提问by Steven

I want to invoke the mainmethod which is static. I got the object of type Class, but I am not able to create an instance of that class and also not able to invoke the staticmethod main.

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

采纳答案by Adeel Ansari

// 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");

In case the method is private use getDeclaredMethod()instead of getMethod(). And call setAccessible(true)on the method object.

如果该方法是私人使用getDeclaredMethod()而不是getMethod(). 并调用setAccessible(true)方法对象。

回答by Frostman

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;
    }
}

回答by atk

Fromthe Javadoc of Method.invoke():

来自 Method.invoke() 的 Javadoc:

If the underlying method is static, then the specified obj argument is ignored. It may be null.
如果底层方法是静态的,则指定的 obj 参数将被忽略。它可能为空。

What happens when you

当你

Class klass = ...;
Method m = klass.getDeclaredMethod(methodName, paramtypes);
m.invoke(null, args)

回答by Hari Krishna

public class Add {
    static int add(int a, int b){
        return (a+b);
    }
}

In the above example, 'add' is a static method that takes two integers as arguments.

在上面的例子中,'add' 是一个静态方法,它接受两个整数作为参数。

Following snippet is used to call 'add' method with input 1 and 2.

以下代码段用于使用输入 1 和 2 调用“添加”方法。

Class myClass = Class.forName("Add");
Method method = myClass.getDeclaredMethod("add", int.class, int.class);
Object result = method.invoke(null, 1, 2);

Reference link.

参考链接