A Simple Java Introduction to Reflection

July 20th, 2012 Leave a comment
Like the article?
A Simple Java Introduction to Reflection

In computer science, reflection is the process by which a computer program can observe, do type introspection and modify its own structure and behavior at runtime.

In many computer architectures, program instructions are stored as data; hence the distinction between instruction and data is merely a matter of how the information is treated by the computer and programming language. Reflection is most commonly used in high-level virtual machine programming languages like Smalltalk and scripting languages, and less commonly used in manifestly typed and/or statically typed programming languages such as Java, C, ML or Haskell.

In this article, we will look at reflection in Java to get information about a class without needing to know the type of class. In the example program below, we take a Java class name as a command line argument and then display all of the methods and field names that are in the class. Here is the code:

package reflectTest;

import java.lang.reflect.*;

public class ReflectionTest {
	public static void main(String[] args) throws Exception {
		if (args.length != 1) {
			String usage = "example usage: ReflectionTest java.util.Calendar";

		Class aClass = Class.forName(args[0]);
		Field[] fields = aClass.getFields();
		System.out.println("Number of Fields = " + fields.length);

		for (int i = 0; i < fields.length; i++) {
			Field field = fields[i];
			System.out.println("[" + field.getName() + "] " 
			+ "with value [" + field.get(aClass) + "]");         

		Method[] methods = aClass.getMethods();
		System.out.println("\nNumber of Methods = " + methods.length);
		for (int i = 0; i < methods.length; i++) {
			Method method = methods[i];
			System.out.println("[" + method.getName() + "] " 
			+ "returns [" + method.getReturnType() + "]");

In the above program, we are accepting a string in the command line and then finding the class by name. The first few lines show an example of usage and then exit if the program is called incorrectly. On line 14, we are locating a match for the class object that was passed in and if it finds one, it is getting an array of all the fields and displaying their name and values. It does the same thing for the methods. As you can see, if it doesn’t find the passed-in class name, it throws an exception.

You may have also noticed the reference on line 21 to field.get(aClass), which is getting the value. This is a useful way of getting the same listed response by passing in an instance of a class object. You would then be able to see the field values for that particular instance, which can be pretty handy. The rest of the program displays the name and return type for each method in the class, which looks like this:

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 one 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.

Help us spread the word!
  • Twitter
  • Facebook
  • LinkedIn
  • Pinterest
  • Delicious
  • DZone
  • Reddit
  • Sphinn
  • StumbleUpon
  • Google Plus
  • RSS
  • Email
  • Print
If you liked this article, consider enrolling in one of these related courses:
Don't miss another post! Receive updates via email!