HomeDigital EditionSys-Con RadioSearch Java Cd
Advanced Java AWT Book Reviews/Excerpts Client Server Corba Editorials Embedded Java Enterprise Java IDE's Industry Watch Integration Interviews Java Applet Java & Databases Java & Web Services Java Fundamentals Java Native Interface Java Servlets Java Beans J2ME Libraries .NET Object Orientation Observations/IMHO Product Reviews Scalability & Performance Security Server Side Source Code Straight Talking Swing Threads Using Java with others Wireless XML

Welcome to the Java Reflection universe. Once you've been there, you'll never think about programming the way you used to.

Imagine that you're a C++ programmer and you have to implement the following program:

1. Ask for a class name.
2. Create an object of that class.
3. Show the field names for the object and their values.

Ouch! As a C++ programmer you'll start thinking about all the tables or if-then-else-if lists you'll have to create. In Java? Forty lines of code, tops! How come? Reflection uses runtime support not present in languages like C or C++. The kinds of things you can do with Reflection can't be done in those languages.

Reflection is a way of thinking; it's a metalanguage that enables you to analyze and manipulate your objects in a dynamic way. Once you see its possibilities, the sky's the limit: serialization, expression evaluation, language interpretation, class factories, object description, plug-in architectures - you name it. Reflection is one of the most exciting features of Java.

Big industrial-strength protocols like SOAP and JavaBeans wouldn't be possible if it weren't for Reflection. Every time you drag-and-drop an object in your favorite IDE into a form, Reflection is orchestrating the action behind the scenes. Actually, most sophisticated Java applications rely on Reflection in one way or another.

Reflection is an advanced feature of the Java environment. It gives runtime information about objects, classes, and interfaces. Reflection answers questions like:

  • Which class does an object belong to?
  • What is the description of a given class name?
  • What are the fields in a given class?
  • What is the type of a field?
  • What are the methods in a class?
  • What are the parameters of a method?
  • What are the constructors of a given class?
Reflection also lets you operate on objects and do things like:
  • Constructing an object using a given constructor
  • Invoking an object's method using such-and-such parameters
  • Assigning a value to an object's field
  • Dynamically creating and manipulating arrays
Now you know the spirit behind Reflection. Let's explore its technical side.

Java Reflection Classes
With the exception of the class Class that resides in the default Java package, all Reflection classes are contained in the package java.lang.reflect.

Classes are represented by the class Class, class Fields by the Field class, methods by the Method class, constructors by the Constructor class, and arrays - you guessed it - by the Array class.

Every class and interface in Java is described by a Class object. There are methods in Class to get all the information about the class: name, parent class, constructors, fields, methods, interfaces implemented, and so on.

To obtain the class that an object belongs to, you call the method Class getClass(). This method is defined in the Object class (root of the Java classes hierarchy) and is therefore available to any object.

String myString = "my string";
Class theClass = myString.getClass();

Every class in Java has a property ".class" that returns a Class object for the class.

if (myString.getClass()==String.class)
System.out.println("The object is a String");

Primitive types such as int or Boolean are represented by Class objects as well. The wrapper classes (Integer, Boolean, Double,...) contain a ".TYPE" property that returns the Class object representing the primitive type. Class Class highlights are shown in Table 1.

Table 1

Class myClass = Integer.TYPE;

The Field class describes the different attributes of a Java class field. From a Field object you can get the field name, its type, and its accessibility. It also contains methods to set and get the field's value for a given object (see Listing 1). Class Field highlights are given in Table 2.

Table 2

The Method class allows you to get information about class methods. You can get the method name, its type, its accessibility, and its parameter types. You can also invoke the method on a particular object and pass a set of parameters to it (see Listing 2). Class Method highlights are given in Table 3.

Table 3

The Constructor class allows you to get information about class constructors such as parameter types, number of parameters, and accessibility. It also lets you invoke the constructor to create new object instances (see Listing 3). Class Constructor highlights are shown in Table 4.

Table 4

Disadvantages and Misuses
I agree that it isn't straightforward to think about thinking. Using Reflection isn't easy at the beginning. The model is simple, but you're using objects called Object, classes called Class, methods called Method..... It takes time to get used to it, but believe me, once you get comfortable with the model, what you can do with Reflection is amazing.

Up to now I've deliberately avoided the subject of exception handling. Almost every Reflection method throws exceptions, making the code very confusing. Not helping the situation is the wrapping/unwrapping of primitive types. What I've done to alleviate this is to create a ReflectionUtilities library that hides all the implementation details and lets me concentrate on my reflective task.

The methods I've introduced so far to access class members work only on public members, by default. If this weren't the case, you could fool the VM and access members illegally, jeopardizing the security of the system. You can change the default behavior, but that implies that you have the right to do so, which isn't usually the case on Web-delivered applications. This forces you to have to declare the class members that you want to expose to Reflection as public. Object-oriented advocates will tell you that this can violate the encapsulation principle.

You can use Reflection in a variety of ways, but sometimes there are better tools to accomplish the same task. Suppose you want to find out whether an object contains a certain method and, if it does, invoke it. You can do this using Reflection (see Listing 4).

Java has a cleaner way to do it, however. Declare an interface that declares the method and implement that interface in the classes that have the method. Then call the method in the following way:

if (anObject instanceof MyInterface) {
// Does anObject implements MyInterface?
((MyInterface) anObject).myMethod();    // If
it does, invoke myMethod()

This code works if you know in advance the classes that will contain myMethod and whether they implement MyInterface. If you don't know, Reflection is the way to go.

Putting Everything Together
Reflection can be used in very different contexts to achieve completely different results. And since you must be eager to see some action at this point, I'll present three cases in which Reflection delivers elegant solutions.

Case 1
Suppose you want to have a function to convert strings into colors. The strings you'd like to pass are color names, and the function should return the appropriate color:

Color myColor = ColorTools. getColorByName( "black" );
// myColor will contain the color Color.black

If you don't use Reflection, you have to maintain a mapping structure that relates color names to Color objects. If the folks at Sun decide tomorrow to introduce the pinkPanther Color constant, you'll have to add it to your map. If there are 10,000 Color constants, the map will be enormous. This is where you can utilize Reflection to analyze the Color class and find its Color constant names and their values. See ColorTools.java in Listing 5 for details. (Because of space considerations, this listing and the corresponding ones for Cases 2 and 3 appear below.)

Case 2
If you develop GUIs in Java, you must be familiar with and probably resigned to using the wordy and annoying anonymous classes to connect component events to their event handlers. Well, there's still hope: by using Reflection you can remove all the anonymous classes.

The trick is to use a naming convention (usually called an idiom by the scholars) to relate the components to their events and then use Reflection to analyze the class, find the components and event handlers, add event listeners, and invoke the event handlers.

Because there's no explicit code in your form that relates handlers to events, the event handlers seem to be called by magic. This is why I like to call this methodology "Magic Couplers." Refer to MagicCoupler.java in Listing 6 to see how to accomplish it - there's no magic after all....

If you adopt this elegant technique, your GUI code will once again be about handling the events, not about connecting event handlers. Magic Couplers have two drawbacks:

1. This one, inherited from the security issues, is the need to declare the components and the event handlers as public so we can access them with Reflection.
2. The connection between events and event handlers is done now at runtime. It means there's no compile-time checking to ensure that the event handlers are named correctly. You can add code (which I removed from the example for brevity) to check that the event handlers correspond to a component and report "unlinked" event handlers.

ReflectionTest.java (see Listing 7) creates a form with a combo box that displays all the color names and two buttons that trigger their event handlers using Magic Couplers (see Figure 1).

Figure 1
Figure  1:

Case 3
Another great use of Reflection is for creating application plug-ins. You can design software that allows you and third-party vendors to create extensions for it. This is accomplished very simply. First, define the plug-in interface that enables you to access the plug-in.

package plugins;

public interface MyApplicationPlugIn {
// Interface definition here

Every plug-in must implement the interface (that's what makes it a plug-in of your application).

package plugins;

public class APlugIn implements MyApplicationPlugIn {
// Interface implementation here

Now you can browse the plug-ins directory to get the plug-in names and dynamically load them by calling:

// plugInNames contains the fully qualified
names of the plug-in classes
for ( int i = 0; i < plugInNames.length; i++ ) {
MyApplicationPlugIn plugIn =
(MyApplicationPlugIn)Class.classFor( plugInNames[i] );
// Do something with the plug-in here

Java Reflection gives you a metalanguage to ask questions and manipulate classes, interfaces, and objects.

The class Class describes the different attributes of Java classes and interfaces in terms of Field, Method, and Constructor objects. These objects in turn let you inspect and manipulate object attributes and create new objects dynamically.

Now that you know the power and dangers of Java Reflection, use it wisely!

Author Bio
José María Barrera is director of Internet applications development at Caminus Corp., a leading software company for the energy sector. A designer/creator of software using Java and XML, José has been involved with computers for the last 17 years. He holds an MS degree in computer science from New York University. [email protected]


Listing 1

java.awt.Point p = new java.awt.Point(10,20);
Class pointClass = p.getClass();                          
// You could call Point.class as well
Field xField = pointClass.getField( "x" );
xField.setInt( p, 3 );  // Set receives an object as its second parameter,
                        // we have to wrap the 3
System.out.println( p.x );                                      
// Will print 3

Listing 2

Class[] parameterTypes = new Class[]{String.class};
Object[] parameterValues = new Object[]{"this line was printed using Reflection"};
// Get the class for System.out
Class class = System.out.getClass();
Method printlnMethod = class.getMethod( "println", parameterTypes );
printlnMethod.invoke( System.out, parameterValues );            
// The string is printed here

Listing 3

Class[] parameterTypes= new Class[]{Integer.TYPE, Integer.TYPE,
Object[] parameters = new Object[]{new Integer( 255 ), new
  Integer( 0 ), new Integer( 0 )};

Class colorClass = Class.forName( "java.awt.Color" );
Constructor colorConstructor = colorClass.getConstructor
  ( parameterTypes );

Object myRedColor = colorConstructor.newInstance( parameters );

Listing 4

try {
// Try to get the method myMethod () from the class of the
      object myObject
        Method myMethod = anObject.getClass().getMethod
   ( "myMethod", new Class[]{} );
// Invoke the method
        myMethod.invoke( myObject, new Object[]{} );
catch ( NoSuchMethodException nSchMetE ) {}
// Thrown by getMethod if the method is not found
catch ( SecurityException secE ) {}
// Thrown by the security manager to indicate a security violation
catch ( IllegalAccessException illAccE ) {}
// Thrown if current method does not have access to myMethod
catch ( IllegalArgumentException illArgE ){}
// Thrown if an argument passed is inappropriate
catch ( InvocationTargetException iTarE) {}
// Thrown if myMethod throws an exception, you can call
//  iTarE.getTargetException() to get the exception.

Download Additional Source Files (~ 845 KB ~Zip File Format)

All Rights Reserved
Copyright ©  2004 SYS-CON Media, Inc.
  E-mail: [email protected]

Java and Java-based marks are trademarks or registered trademarks of Sun Microsystems, Inc. in the United States and other countries. SYS-CON Publications, Inc. is independent of Sun Microsystems, Inc.