[英]String to method (invoke) throws an Exception
I want to call a method, given a String. 我想调用一个给定字符串的方法。 I mean, I have a String which is the name of the method I want to call.
我的意思是,我有一个String,这是我要调用的方法的名称。
I've seen that the reflection is the way to meet the target but, when I try to get the method (before invoking it), I get an exception. 我已经看到反射是达到目标的方式,但是,当我尝试获取方法(调用它之前)时,出现了异常。
That's what I have done: 那就是我所做的:
Method method = Object.class.getMethod("functionToCall", String.class);
Why is this command throwing an exception? 为什么此命令引发异常? What can I do in order to get the method which is going to be invoked?
为了得到将要调用的方法,我该怎么办?
Thank you very much in advance! 提前非常感谢您!
What you are trying in your example is to get the functionToCall
method which takes a String
as parameter from java.lang.Object
class. 在示例中,您要尝试的是获取
functionToCall
方法,该方法将java.lang.Object
类中的String
作为参数。 It won't happen. 不会发生的
However you can use getMethod()
and the invoke()
combination like this: 但是,您可以像下面这样使用
getMethod()
和invoke()
组合:
The class to work with: 要使用的课程:
public class MyClass {
public void myMethod(final String pString) {
System.out.println("Hello "+pString);
}
}
And to actually invoke the method 并实际调用该方法
// 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");
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.