字符串到方法(调用)抛出异常

String to method (invoke) throws an Exception

我想调用一个给定字符串的方法。我的意思是,我有一个字符串,它是我要调用的方法的名称。

我已经看到反射是达到目标的方式,但是,当我尝试获取该方法时(在调用它之前),我得到一个异常。

这就是我所做的:

        Method method = Object.class.getMethod("functionToCall", String.class);

为什么这个命令抛出异常?我该怎么做才能获得将要调用的方法?

非常感谢您!

您在示例中尝试的是从 java.lang.Object class 获取 functionToCall 方法,该方法将 String 作为参数。不会发生的。

但是您可以像这样使用 getMethod()invoke() 组合:

要合作的class:

public class MyClass {
    public void myMethod(final String pString) {
        System.out.println("Hello "+pString);
    }
}

并实际调用方法

// We get the method myMethod which takes a String.
Method method = MyClass.class.getMethod("myMethod", String.class);
// We call it on a new MyClass instance with "Test" as parameter.
method.invoke(new MyClass(), "Test");