Open In App

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

Last Updated : 18 Oct, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Java Reflection API provides us information about a Class to which the Object belongs to including the methods in this class. Using these Reflection API we would be able to get invoking pointer for a method in a class with its name.

There are two functions used for this purpose:

  1. Invoking method with its name
  2. Finding a method by Name in a class and invoking the same

1. Invoking method with its name

getDeclaredMethod() is used for this purpose

Syntax

Class.getDeclaredMethod(“method name”, parameterType)

Method name: the method we want to find by name 

Parameter Type: Type of parameters the method accepts

Return Type: This method would return an object with reference to the method’s address which would then be used to invoke the method. We would use invoke method for this

If there are many overloaded methods with the same name, the compiler would invoke the method matching the parameter

Invoke function

Would be used to invoke the method using the Method object

Syntax

Method.invoke(classObj, param1, param2…)

methodObj: Object of method returned from the getDeclaredMethod  

Parameters: parameter values used to invoke the method. If the method does not have any parameters to be passed, then we would pass null here

Example

Java




// Java program to invoke method with its name
// using Reflection API
  
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
  
class GFG {
    public void printMessage(String message)
    {
        System.out.println(
            "you invoked me with the message:" + message);
    }
    
    public static void main(String[] args) throws Exception
    {
        System.out.println("Invoke method by Name in Java using Reflection!");
        
        // create class object to get its details
        GFG obj = new GFG();
        
        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, "hello"); 
        }
        
        catch (InvocationTargetException e) 
        {
            System.out.println(e.getCause());
        }
    }
}


Output

Invoke method by Name in Java using Reflection!
you invoked me with the message:hello

2. Finding a method by Name in a class and invoking the same

In case we don’t know the exact method parameters, we could also get all the methods in the class and search through the method by its name and then get details of it  

  • We would use getDeclaredMethods() API for the same. This would return array of Method objects in the class
  • We can use this to loop through the Method objects and find the method by its name using the getName().
  • Then we would use the getGenericParameterTypes() to find the parameter it takes and getGenericReturnType() to find its return type
  • Once we have the parameter and return type, we would use our invoke function mentioned above to invoke the method

Syntax

Method[] methods = Class.getDeclaredMethods()  

Example:

Java




// Java program of Finding a method by Name in a class
// and invoking the same
  
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
  
class GeeksForGeeks {
    public void printMessage(String message)
    {
        System.out.println(
            "you invoked me with the message:" + message);
    }
  
    public void addMe(int num1, int num2)
    {
        System.out.println("sum is:" + (num1 + num2));
    }
  
    public static void main(String[] args) throws Exception
    {
        System.out.println("Find method by Name in Java using Reflection!");
        
        // create class object to get its details
        GeeksForGeeks obj = new GeeksForGeeks();
        
        Class classObj = obj.getClass();
  
        // get all methods in the class
        Method[] allMethods = classObj.getDeclaredMethods();
  
        // loop through the methods to find the method addMe
        for (Method m : allMethods) {
            
            String methodName = m.getName();
            if (methodName.equals("addMe")) {
                try {
                    
                    // invoke the method directly with its
                    // parameters
                    m.invoke(obj, 10, 20);
                }
                catch (InvocationTargetException e) {
                }
            }
        }
    }
}


Output

Find method by Name in Java using Reflection!
sum is:30

Exception thrown by invoke method

Invoke method would throw InvocationTargetException when the underlying method being invoked throws an exception. We would be able to retrieve the method’s exception by using getCause() method of InvocationTargetException



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads