Ask Your Question
0

What is the process for invoking a method in a class by its name while passing arguments?

asked 2023-05-25 07:15:49 +0000

ladyg gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
0

answered 2023-05-25 07:32:02 +0000

scrum gravatar image

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();
}
edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2023-05-25 07:15:49 +0000

Seen: 10 times

Last updated: May 25 '23