How do I invoke a Java method when given the method name as a string?
Answers
Explanation:
You can invoke the method using the class named method of the package java.lang.reflect. The constructor of this class accepts the method name in the form of a string. And you can invoke this method using the invoke() method.
A Method permits widening conversions to occur when matching the actual parameters to invoke with the underlying method's formal parameters, but it throws an IllegalArgumentException if a narrowing conversion would occur.
You can invoke the method using the class named method of the package java.lang.reflect. The constructor of this class accepts the method name in the form of a string. And you can invoke this method using the invoke() method.
Example:-
import java.lang.reflect.Method;
public class DemoTest {
private void sampleMethod(){
System.out.println("hello");
}
}
public class SampleTest {
public static void main(String args[]) throws Exception{
Class c = Class.forName("DemoTest");
Object obj = c.newInstance();
Method method = c.getDeclaredMethod("sampleMethod", null);
method.setAccessible(true);
method.invoke(obj, null);
}
}