Java Reflection Invoke Static Method

This article will look at how we can use Java Reflection API to invoke a Static method. We will see the steps and the explanation with code. Let us first have a quick look at Reflection API.

Reflection in Java is a process of examining or modifying the behavior of a class at run time. Moreover, It is an API or Application Programming Interface having its use in debugging. It is also used in testing tools, with the primary focus on changing the runtime behavior of a class. In Java, The Package java.lang.Reflect provides the classes and interface to obtain reflective information about classes and objects.

Now, the task is to invoke a Static method using Reflection in Java. Consider this class StudentDetails:

Here, we have two static methods one gets the details of a student and one gives the total number of students. As you can see both are static methods and we have to invoke these two methods in our Main class or Controller and execute them without creating an Object of the Class.

Invoking Static Method

So to invoke the Static Methods of StudentDetails Class without creating an instance we follow the steps highlighted below:

  • Create a Class Object: We create a Class Object of Type StudentDetails using the .class keyword.
  • Get The Method: Next, we get the required methods from the StudentDetails class with the Class Object we created. We use a Method object of class java.lang.reflect.Method. We invoke the getMethod() of the Class Object which returns the specified method of class as a Method Object.

The General Syntax is: public Method getMethod(String MethodName, ParameterType.class)

Note: If the Parameter to pass while invoking is of type String Array, we give the second argument as String[].class and if it is an Integer we use Integer.class. Also, the getMethod throws NoSuchMethodException and SecurityException which need to be handled explicitly.

  • Invoke Method: After this, we invoke the static method using invoke() method of the Method object. The General Syntax: public Object invoke(Object ClassObject, Object Parameters) 

Note: Here, as the method is static we don’t need a Class Object so the first argument is null, In Method Parameters, we typecast the parameter as Object Type for any Object type parameter. The Primitive data types are automatically passed as a Wrapper class Object.

Let us have a look at the implementation of the Main Class or StudentController in code.

Output:

So we can see without actually creating an Object of StudentDetails Class we can invoke its static method using the Reflection mechanism.

That’s all about the article, you can try executing the code with both classes in separate files (suggested) or in the same and let us know in the comment section for any queries.

Leave a Reply

Your email address will not be published. Required fields are marked *