Simple Introduction to Reflection

by Mark Shead on February 22, 2005

Reflection is a mechanism in java that allows to to get information about a class without needing to know the type of the class. The program below takes a java class name as a command line argument and shows you all of the methods and field names that are in the class.

You call the sample program like this:
java ReflectionTest java.util.Calendar

ReflectionTest takes the string you pass in on the command line and attempts to find a class by that name. If it finds one it gets an array of all the fields and displays their name and their values. It then gets an array of all the methods and displays their name and their return type.

Notice that the Calendar class doesn’t appear anywhere in the code. Reflection allows you to look inside a class without needing to know what the class is. You can use reflection to create objects that can work with classes that they don’t ever know about directly.


01 package test;
02 import java.lang.reflect.*;
03 
04 public class ReflectionTest{
05 
06     public static void main(String[] argsthrows Exception {
07         if(args.length != 1) {
08             String usage = "example usage: ReflectionTest java.util.Calendar";
09             System.out.println(usage);
10             System.exit(0);
11         }
12         Class aClass = Class.forName(args[0]);
13         Field[] fields = aClass.getFields();
14         System.out.println("Number of Fields = " + fields.length);
15         for(int i = 0; i < fields.length; i++){
16             Field field = fields[i];
17             System.out.println("[" + field.getName() "] " 
18                   "with value [" + field.get(aClass"]");         
19         }
20         
21         Method[] methods = aClass.getMethods();
22         System.out.println("\nNumber of Methods = " + methods.length);
23         for(int i = 0; i < methods.length; i++){
24             Method method = methods[i];
25             System.out.println("[" + method.getName() "] " 
26                     "returns [" + method.getReturnType() "]");
27         }
28         
29     }
30 }

Lines 7 through 10 are just to show the usage and exit if the program is called incorrectly. In line 12, we get the class object that matches the name passed in on the command line. If it can't find it an exception is thrown. For the purposes of this example I just have main throwing the exception.

On line 13 we use the class to get the fields and then print out their name and value in 15 to 19. Notice the odd reference of field.get(aClass) to get the value. It seems odd in this example because we are just passing it a class. You could also pass it a real live instance of a Calendar object and it would tell you what the field values are for that instance of Calendar.

The remaining code uses the same process to get the name and return type of each method in the class.

Here are the results of the program being run on java.util.Calendar as an argument:


Number of Fields = 41
[ERA] with value [0]
[YEAR] with value [1]
[MONTH] with value [2]
[WEEK_OF_YEAR] with value [3]
[WEEK_OF_MONTH] with value [4]
[DATE] with value [5]
[DAY_OF_MONTH] with value [5]
[DAY_OF_YEAR] with value [6]
[DAY_OF_WEEK] with value [7]
[DAY_OF_WEEK_IN_MONTH] with value [8]
and so on.......

Number of Methods = 46
[hashCode] returns [int]
[equals] returns [boolean]
[toString] returns [class java.lang.String]
[get] returns [int]
[clone] returns [class java.lang.Object]
[add] returns [void]
[isSet] returns [boolean]
and so on ...

Reflection is oen of the tools that frameworks utilize to make things happen automatically. For example, if you create a Java Bean you can make a .JSP page automatically take form values and populate the bean using the setter methods. When Tomcat was being written they couldn’t predict what your particular object would look like, so they used reflection to look inside your object and find the appropriate methods to call.

Reflection is a good way to build future-proof functionality. You can come up with a way of doing something that will work with any class you give it without needing to know about that class ahead of time or force the class to implement an interface.

It is a powerful tool that can help you achieve a great deal of simplicity. Automatically setting the values of a bean from a form in JSP is a good example of how reflection can simplify your code.

Here are a few links to discussions about reflection.

About 

{ 1 comment… read it below or add one }

Jinesh May 9, 2006 at 7:05 am

hai
I am having a private method like
private boolan exceute(Object ,String)
whenever i tried to access this private method
like
Method method = c.getMethod(
“execute”, classTypes);
method.setAccessible(true);
Protor pt = new Protor();
Object meth = method.invoke(pt, args);
i am getting an invocationtargetexception
why is it so
Please help

Reply

Leave a Comment

Previous post:

Next post: