Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The process for invoking a method in a class by its name while passing arguments involves the following steps:

  1. Get the Class object of the class containing the method using the Class.forName() method or the getClass() method on an instance of the class.
  2. Get the Method object of the method to be invoked using the getMethod() or getDeclaredMethod() method of the Class object. The getMethod() method only returns public methods while the getDeclaredMethod() method returns all methods including private ones.
  3. Invoke the method using the invoke() method of the Method object and passing the necessary arguments.
  4. Handle any potential exceptions thrown during the process.

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();
}