1 | initial version |
The process for invoking a method in a class by its name while passing arguments involves the following steps:
Here's an example:
//class with the method to be invoked
public class Calculator {
public int add(int a, int b) {
return a + b;
}
}
//invoking the method by its name and passing arguments
try {
Class<?> clazz = Class.forName("Calculator");
Method method = clazz.getMethod("add", int.class, int.class);
Object instance = clazz.newInstance();
int result = (int) method.invoke(instance, 2, 3);
System.out.println(result); //prints 5
} catch (Exception e) {
e.printStackTrace();
}