How do I invoke a Java method when given the method name as a string?
To invoke a Java method when given the method name as a string, you can use reflection. Reflection is a feature of the Java language that allows you to inspect and manipulate classes, fields, and methods at runtime.
Here is an example of how you can use reflection to invoke a method in Java:
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
String methodName = "someMethod";
SomeClass obj = new SomeClass();
Method method = obj.getClass().getMethod(methodName);
method.invoke(obj);
}
}
This code gets the Method
object for the method with the name someMethod
in the SomeClass
class, and then invokes the method on an instance of SomeClass
.
Note that this example assumes that the method is a public instance method, and that it takes no arguments. If the method has different visibility or takes arguments, you will need to use different methods to get the Method
object. You can also use the Method.setAccessible(true)
method to make a private or protected method accessible.
Here is an example of how you can invoke a private method with arguments:
import java.lang.reflect.Method;
public class Main {
public static void main(String[] args) throws Exception {
String methodName = "someMethod";
SomeClass obj = new SomeClass();
Method method = obj.getClass().getDeclaredMethod(methodName, int.class, String.class);
method.setAccessible(true);
method.invoke(obj, 42, "hello");
}
}
This code gets the Method
object for the private method someMethod
that takes an int
and a String
as arguments, makes the method accessible, and then invokes it on an instance of SomeClass
with the arguments 42
and "hello"
.