How to Invoke Method by Name in Java Dynamically Using Reflection?
With the Java Reflection API, developers can run operations on the members of a Java class, such as its methods, fields, and constructors, while the program is running. This enables them to modify the behaviour of a class at runtime, rather than having to rely on the class’s code being fixed beforehand. This can be useful for a variety of purposes, such as creating custom frameworks or testing the behaviour of different implementations of a particular interface.
With the Reflection API, developers can dynamically call methods, access and modify fields, and even instantiate new objects without knowing their names or the types of their arguments at compile time.
This is useful when working with third-party libraries or code without the source code. It inspects and manipulates Java program runtime behaviour.
Two functions used for this purpose
Invoking method with its name
Using the Java Reflection API, you can call a method by name by using the Class.getMethod()
function to get a Method object and then calling the Method object. invoke()
function to invoke the method on an object.
Find a method by name in a class and invoke it
Use the Class.getMethod()
function of the Java Reflection API to find a method in a class by its name. This will return a Method object with the specified name for the first public method. If there are multiple methods with the same name but different types of parameters, you can tell `getMethod() how the parameters are typed to tell them apart.
Invoking the method by its name
Syntax
Class.forName("classname").getMethod("methodname", parameterTypes).invoke(object, arguments)
Code language: Java (java)
Output
The output of the method will be returned by the invoke method. The type of the returned value depends on the return type of the method. In the above example, the method returns a String
, so the returned value is stored in a String
variable.
Find a method by name in a class and invoke it
Syntax
Class.forName("classname").getMethod("methodname", parameterTypes).invoke(object, arguments)
Code language: Java (java)
Output
The output of the method will be returned by the invoke
method. The type of the returned value depends on the method’s return type. In the above example, the method returns a String
, so the returned value is stored in a String
variable.
Java Program to invoke method by name dynamically using Reflection
Here is a sample Java program that demonstrates how to invoke a method by its name dynamically using reflection:
import java.lang.reflect.Method;
public class Example {
public static void main(String[] args) throws Exception {
// Get the class object for the class that contains the method
Class<?> cls = Class.forName("example.ExampleClass");
// Get the method object for the method we want to invoke
Method method = cls.getMethod("exampleMethod", String.class);
// Create an instance of the class
Object obj = cls.newInstance();
// Invoke the method on the instance, passing in any necessary arguments
String result = (String) method.invoke(obj, "example argument");
System.out.println(result);
}
}
Code language: Java (java)
Important points while calling Java method using reflection
- The method you want to invoke must be public and accessible from the calling class.
- You must have the correct number and types of arguments to invoke the method.
- If the method you are trying to invoke throws an exception, it will be wrapped in an InvocationTargetException and must be caught and handled appropriately.
Exception thrown by invoke method
The invoke() method of the Method class can throw a variety of exceptions, including:
- IllegalAccessException: This exception is thrown if the method is not accessible from the calling class.
- IllegalArgumentException: This exception is thrown if the number or type of arguments passed to the invoke() method do not match the method’s signature.
- InvocationTargetException: If the invoked method throws an exception. InvocationTargetException’s getCause() method returns the original error.
Example program for invoking the methods of a class using Reflection Framework
Here’s an example of a Java program that shows how to use the Java Reflection API to call a class’s methods at runtime based on what’s going on at that moment:
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// Load the class using its fully qualified name
Class<?> clazz = Class.forName("java.util.ArrayList");
// Get a reference to the add() method
Method addMethod = clazz.getMethod("add", Object.class);
// Create an instance of the class
Object list = clazz.newInstance();
// Invoke the add() method on the instance
addMethod.invoke(list, "Hello");
addMethod.invoke(list, "World");
// Get a reference to the size() method
Method sizeMethod = clazz.getMethod("size");
// Invoke the size() method and print the result
System.out.println("Size: " + sizeMethod.invoke(list));
// Get a reference to the get() method
Method getMethod = clazz.getMethod("get", int.class);
// Invoke the get() method and print the result
System.out.println("First element: " + getMethod.invoke(list, 0));
System.out.println("Second element: " + getMethod.invoke(list, 1));
} catch (Exception e) {
e.printStackTrace();
}
}
}
Code language: Java (java)
Output
Example of calling “append” method of StringBuffer class
Here’s how reflection can call StringBuffer’s add() method:
import java.lang.reflect.Method;
public class ReflectionExample {
public static void main(String[] args) {
try {
// Load the class using its fully qualified name
Class<?> clazz = Class.forName("java.lang.StringBuffer");
// Get a reference to the append() method
Method appendMethod = clazz.getMethod("append", String.class);
// Create an instance of the class
Object buffer = clazz.newInstance();
// Invoke the append() method on the instance
appendMethod.invoke(buffer, "Hello");
appendMethod.invoke(buffer, "World");
// Get a reference to the toString() method
Method toStringMethod =clazz.getMethod("toString");
// Invoke the toString() method and print the result
System.out.println(toStringMethod.invoke(buffer));
}
catch (Exception e) {
e.printStackTrace();
}
}
}
Code language: Java (java)
Output
This application generates a StringBuffer instance and calls append() and toString() via reflection. Program output is “HelloWorld.”
Conclusion
Java’s reflection technology permits dynamic method invocation at runtime. This is helpful when you only know the method name once runtime or wish to launch a method based on user input. Reflection can reduce code readability and maintainability, so use it carefully.
FAQ’s- Frequently Asked Questions
How is a method called using reflection?
To call a method using reflection, you must first get a Method object from the Class object by calling getMethod() or getDeclaredMethod(). Using the Method object’s invoke() method, you can call the method.
In Java, is it possible to invoke a method by class name?
Yes, you can call a method using a class name in Java by obtaining the Class object of that class and then using the reflection API to call the method of that class.
What are the Java methods for calling a method?
Java’s reflection API, Method Handles, and JSL API can invoke a method.
What is invoke dynamic in Java?
Invoke dynamic is a feature of the Java language that allows for the dynamic behavior of method invocation by passing the name of the method and its arguments at run-time.
What are two ways of invoking methods?
The two ways of invoking methods are either through the use of the invocation API or through the use of the standard Java library API.
Sharing is caring
Did you like what NIKESH JAGDISH MALIK wrote? Thank them for their work by sharing it on social media.
No comments so far
Curious about this topic? Continue your journey with these coding courses: