Java Reflection API provides support for querying information about a class at run-time. This information includes the list of public as well as private members (methods) available for the class, the various public operations it supports etc. This section will guide you in making use of the Reflection API. Suppose we have the following test class containing two methods,
also read:
- Java Tutorials
- Java EE Tutorials
- Design Patterns Tutorials
- Java File IO Tutorials
TestClass.java
package tips.reflection; public class TestClass { public int a = 10; private int b = 32; public String name = "TestClass"; public void method1(){ System.out.println("Method1 is called. a = " + a); } public void method3(){ System.out.println("Method3 is called. name = " + name); privateMethod(); } private void privateMethod(){ System.out.println("A private method "); } }
If we want to get the class information for TestClass
, then we have the following program. The following program dynamically loads the TestClass
by calling the Class.forName("className")
. It should be noted that while specifying the class name within Class.forName()
, the fully qualified name of the class (i.e package name + class name) should be specified. Then to retrieve all the defined methods in the class, a call is made to Class.getDeclaredMethods()
which returns all the methods as an array. Same happens while retrieving the fields.
The next block of code performs dynamic invocation of the method method1
. It first gets a reference to the method method1
by calling Class.getMethod("method1")
. Then using the Method.invoke()
method, an invocation is performed on the method1
method by passing the original object along with an array of arguments the method is going to accept. Since in our case, the method method1
doesn’t accept any arguments an empty Object array is passed to the Method.invoke()
method.
ReflectionTest.java
package tips.reflection; import java.lang.reflect.Field; import java.lang.reflect.Method; public class ReflectionTest { public static void main(String[] args) throws Exception { Class<?> classObject = Class.forName("tips.reflection.TestClass"); Method allMethods[] = classObject.getDeclaredMethods(); for(Method aMethod : allMethods){ System.out.println("method : " +aMethod.getName()); } Field allFields[] = classObject.getDeclaredFields(); for(Field aField : allFields){ System.out.println("field : " +aField.getName()); } Object testClass = classObject.newInstance(); Method aMethod1 = classObject.getMethod("method1", new Class[]{}); aMethod1.invoke(testClass, new Object[]{}); } }
The output of the above code is,
method : method1 method : method3 method : privateMethod field : a field : b field : name Method1 is called. a = 10
In this section, we saw a simple example of using Reflection API. This API can be further explored and be effectively utilized based on our needs.