I am trying to use a string to call a method?
Suppose I have a class called Kyle which has 3 methods:
public void Test();
public void Ronaldo();
public void MakeThis();
And I have a string with the name of the method which I need to call:
String text = "Test()";
Now I need to call the method whose name is inside of this string:
Kyle k = new Kyle();
k.text;?
You’ll need to use java
Reflectionto do this.See: Class.getMethod()
Using your specific example:
That’s without the exception handling required for
getMethod()andMethod.invoke(), and only covers the case of calling methods that take no arguments.See also: