How to Invoke Method by Name in Java Dynamically Using Reflection?


The Reflection API in Java allows you to dynamically call any method using its string name. When using the java.lang.reflect API, you can load classes by name even if they aren't accessible at compile time thanks to reflection's robust mechanism. It empowers you to dynamically invoke any method using reflection and makes it possible you to retrieve all methods from a class, including private and public ones.

Those who are unfamiliar with Java might find this idea strange. With no explicit code for calling the method during compilation, Java can execute a method when its name is provided as a string at runtime. Reflection is an effective mechanism that enables you to carry out different tasks flexibly.

Methods Used

There are two functions used here −

  • Calling a method by its name

  • Locating a method by name within a class and calling it

Method 1: Calling the method with its name

The getDeclaredMethod() function can be used to call a method by its name. It has the following syntax.

Syntax

Class.getDeclaredMethod("method name", parameterType)

"method name" in this syntax means the name of the method you are looking for.

The method's parameterType specifies the parameters types it will accept.

The function takes a call and returns an object which contains the address of the method. The method will later be called using this object. The invoke method would be used to call the method. The method is originally called using the Method object obtained from getDeclaredMethod by using the invoke function ().

It has the following syntax −

Syntax

methodObj.invoke(classObj, param1, param2...)

Acquiring MethodObj from invoking getDeclaredMethod() enables us to perform an invocation of our desired selected method with ease.

The parameters param1, param2, and so forth display the values of the parameters that should be handed to the method. When the method has no parameters, you can bypass null.

getDeclaredMethod()

The program demonstrates how to invoke a method by its name using the Reflection API in Java. It creates "Tutorialspoint" class with "printMessage" method that prints a message. In the main method, it obtains the method object for "printMessage" using the class object and invokes it with a message. The output shows the successful invocation of the method with the provided message.

Algorithm

  • Import the necessary Java packages.

  • Come up with a class called Tutorialspoint with a printMessage() method that takes a String parameter.

  • Come up with a main() method that prints a message and creates a Tutorialspoint object.

  • Obtain the Class object for the Tutorialspoint class.

  • Get the Method object for the printMessage() method.

  • Invoke the printMessage() method on the Tutorialspoint object, passing in a String parameter.

  • Catch any InvocationTargetExceptions and print the cause if any.

  • The program will print the output messages indicating the successful invocation of the method.

Example

// Java program for invoking method with its name with Reflection API

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class Tutorialspoint {
   public void printMessage(String message){
      System.out.println("you called on me with the message:" + message);
   }

   public static void main(String[] args) throws Exception{
      System.out.println("Java uses Reflection to allow you to invoke a method by name!");

      // create class object to get its details
      Tutorialspoint obj = new Tutorialspoint();

      Class<?> classObj = obj.getClass();

      // get method object for "printMessage" function by
      // name
      Method printMessage = classObj.getDeclaredMethod("printMessage", String.class);

      try {
         // invoke the function using this class obj
         // pass in the class object
         printMessage.invoke(obj, "Welcome Students");
      }
      catch (InvocationTargetException e){
         System.out.println(e.getCause());
      }
   }
}

Output

Java uses Reflection to allow you to invoke a method by name!
you called on me with the message:Welcome Students

Method 2: Locating a method by name within a class and calling it

If we are unsure of the exact method parameters, we may employ the getDeclaredMethods() API to retrieve all of a class's methods. This API returns an array of Method objects, which we can manipulate.

Use a loop to iterate over these Method gadgets and use the getName() method to locate a specific technique by way of name. You can get greater records about the method's parameters the usage of the getGenericParameterTypes() technique and the getGenericReturnType() method to get more statistics approximately its return type. Once we have the vital statistics approximately the parameters and return type of the approach, we will use the invoke feature noted earlier than calling the method.

Using this method, we can dynamically search a path and obtain its information without having to know its exact parameters in advance.

Syntax

Method[] methods = Class.getDeclaredMethods()

numAdd()

The program demonstrates how to find a method by its name using the Reflection API in Java. It creates a class "Tutorialspoint" with two methods: "printMessage" and "numAdd". In the main method, it obtains the class object of the "Tutorialspoint" object and retrieves all declared methods using getDeclaredMethods(). It then iterates through the methods and checks if the method name is "numAdd". If it matches, it invokes the method with provided integer parameters using the invoke() method. The output shows the successful invocation of the "numAdd" method and prints the sum of the provided numbers.

Algorithm

  • Step 1 − Create a class named "Tutorialspoint" with two methods: "printMessag." It will take a string parameter and prints a message, and "numAdd" that takes two integer parameters and prints their sum.

  • Step 3 − Inside the "numAdd" method, print the sum of the two numbers.

  • Step 4 − In the main method, print a message indicating that finding a method by name in Java is done using Reflection.

  • Step 4 − Create an object of the "Tutorialspoint" class.

  • Step 5 − Get the class object of the created object with the help of the getClass() method.

  • Step 6 − Get all methods declared in the class with the help of the getDeclaredMethods().

  • Step 7 − Iterate through each method using a for-each loop.

  • Step 8 − Check if the method name equals "numAdd".

  • Step 9 − If it matches, invoke the method directly with the provided parameters using the invoke() method, passing the object and the parameter values.

  • Step 10 − If an exception occurs during method invocation, catch the InvocationTargetException.

  • Step 11 − The program will print the output message indicating the successful method invocation and the sum of the provided numbers.

Example

import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;

public class Tutorialspoint {
   public void printMessage(String message){
      System.out.println("you called on me with the message:" + message);
   }

   public void numAdd(int num1, int num2){
      System.out.println("total is:" + (num1 + num2));
   }

   public static void main(String[] args) throws Exception{
      System.out.println("Using Java's Reflection, discover a method by name.");

      // create class object for obtaining its details
      Tutorialspoint obj = new Tutorialspoint();

      Class classObj = obj.getClass();

      // get all methods in the class
      Method[] allMethods = classObj.getDeclaredMethods();

      // loop through the methods to look for the method numAdd()
      for (Method m : allMethods) {
         String methodName = m.getName();
         if (methodName.equals("numAdd")) {
            try {
               // invoke the method directly with its
               // parameters
               m.invoke(obj, 20, 30);
            }
            catch (InvocationTargetException e) {
            }
         }
      }
   }
}

Output

Using Java's Reflection, discover a method by name.
total is:50

Conclusion

Reflection can be used to dynamically invoke methods by name. It may be useful for debugging, producing code, and extending existing training. However, it's miles important to use reflection with caution, as it may be risky if no longer used properly.

Updated on: 18-Oct-2023

101 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements