How to Invoke Method by Name in Java Dynamically Using Reflection?
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:
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
- Invoking method with its name
- Finding a method by Name in a class and invoking the same
1. Invoking method with its name
getDeclaredMethod() is used for this purpose
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
Would be used to invoke the method using the Method object
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
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
Method methods = Class.getDeclaredMethods()
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