| By Jose Barrera | Article Rating: |
|
| September 1, 2001 12:00 AM EDT | Reads: |
30,796 |
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?
- 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
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.
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.
Class myClass = Integer.TYPE;
Field
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.
Method
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.
Constructor
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.
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 only on the Web at www.sys-con.com/java/sourcec.cfm.)
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).
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
...
}
Summary
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!
Published September 1, 2001 Reads 30,796
Copyright © 2001 SYS-CON Media, Inc. — All Rights Reserved.
Syndicated stories and blog feeds, all rights reserved by the author.
More Stories By Jose Barrera
José María Barrera is the Director of Internet Applications Development at Caminus Corp., a leading software company for the Energy Sector. He designs and creates software using Java and XML. José has been involved with computers for the last 17 years and earned a M.S. degree in Computer Science from NYU. You can contact him at jose.barrera@caminus.com.
- Cloud People: A Who's Who of Cloud Computing
- New Relic Q1 2013 Blazes Past Growth Targets and Reaches 40,000 Active Customer Accounts
- Cloud Expo New York: Delivering Digital Marketing on the Cloud
- Cloud Expo New York: Rethink IT and Reinvent Business with IBM SmartCloud
- Cloudant to Exhibit at Cloud Expo & Big Data Expo New York
- The Accessibility of the Cloud
- Learn How To Use Google Apps Script
- Cloud Expo NY: Best Practices for Delivering Oracle Database as a Service
- Cloud Expo New York: Basics of SSD Technology and Its Use in Cloud
- Session Topics: 12th Cloud Expo / Cloud Expo New York
- Cloud Expo New York: The Big Challenge of Big Data & Hadoop Integration
- Measuring the Business Value of Cloud Computing
- Cloud People: A Who's Who of Cloud Computing
- Cloud Expo New York: Best CIO Practices Shared from SHI’s Customers
- Cloud Expo New York: How to Use Google Apps Script
- New Relic Q1 2013 Blazes Past Growth Targets and Reaches 40,000 Active Customer Accounts
- Cloud Expo New York: Why Big Data Is Really About Small Data
- Cloud Expo New York: Delivering Digital Marketing on the Cloud
- Small Cancers, Big Data, and a Life Examined
- Cloud Expo New York: Requirements of a Cloud Database
- Cloud Expo New York: Rethink IT and Reinvent Business with IBM SmartCloud
- Cloudant to Exhibit at Cloud Expo & Big Data Expo New York
- The Accessibility of the Cloud
- Learn How To Use Google Apps Script
- A Cup of AJAX? Nay, Just Regular Java Please
- Java Developer's Journal Exclusive: 2006 "JDJ Editors' Choice" Awards
- JavaServer Faces (JSF) vs Struts
- The i-Technology Right Stuff
- Rich Internet Applications with Adobe Flex 2 and Java
- Java vs C++ "Shootout" Revisited
- Bean-Managed Persistence Using a Proxy List
- Reporting Made Easy with JasperReports and Hibernate
- Creating a Pet Store Application with JavaServer Faces, Spring, and Hibernate
- Why Do 'Cool Kids' Choose Ruby or PHP to Build Websites Instead of Java?
- What's New in Eclipse?
- Where Are RIA Technologies Headed in 2008?























