Welcome!

Java Authors: Torben Andersen, Sergio Varga, Liz McMillan, Elizabeth White, Patrick Carey

Related Topics: Java

Java: Article

What is Java Reflection?

What is Java Reflection?

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.

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!

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 [email protected]

Comments (0)

Share your thoughts on this story.

Add your comment
You must be signed in to add a comment. Sign-in | Register

In accordance with our Comment Policy, we encourage comments that are on topic, relevant and to-the-point. We will remove comments that include profanity, personal attacks, racial slurs, threats of violence, or other inappropriate material that violates our Terms and Conditions, and will block users who make repeated violations. We ask all readers to expect diversity of opinion and to treat one another with dignity and respect.


@ThingsExpo Stories
“In the past year we've seen a lot of stabilization of WebRTC. You can now use it in production with a far greater degree of certainty. A lot of the real developments in the past year have been in things like the data channel, which will enable a whole new type of application," explained Peter Dunkley, Technical Director at Acision, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
The BPM world is going through some evolution or changes where traditional business process management solutions really have nowhere to go in terms of development of the road map. In this demo at 15th Cloud Expo, Kyle Hansen, Director of Professional Services at AgilePoint, shows AgilePoint’s unique approach to dealing with this market circumstance by developing a rapid application composition or development framework.
The major cloud platforms defy a simple, side-by-side analysis. Each of the major IaaS public-cloud platforms offers their own unique strengths and functionality. Options for on-site private cloud are diverse as well, and must be designed and deployed while taking existing legacy architecture and infrastructure into account. Then the reality is that most enterprises are embarking on a hybrid cloud strategy and programs. In this Power Panel at 15th Cloud Expo (http://www.CloudComputingExpo.com), moderated by Ashar Baig, Research Director, Cloud, at Gigaom Research, Nate Gordon, Director of T...
"BSQUARE is in the business of selling software solutions for smart connected devices. It's obvious that IoT has moved from being a technology to being a fundamental part of business, and in the last 18 months people have said let's figure out how to do it and let's put some focus on it, " explained Dave Wagstaff, VP & Chief Architect, at BSQUARE Corporation, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4-6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Windstream, a leading provider of advanced network and cloud communications, has been named “Silver Sponsor” of SYS-CON's 16th International Cloud Expo®, which will take place on June 9–11, 2015, at the Javits Center in New York, NY. Windstream (Nasdaq: WIN), a FORTUNE 500 and S&P 500 company, is a leading provider of advanced network communications, including cloud computing and managed services, to businesses nationwide. The company also offers broadband, phone and digital TV services to consumers primarily in rural areas.
The Internet of Things is not new. Historically, smart businesses have used its basic concept of leveraging data to drive better decision making and have capitalized on those insights to realize additional revenue opportunities. So, what has changed to make the Internet of Things one of the hottest topics in tech? In his session at @ThingsExpo, Chris Gray, Director, Embedded and Internet of Things, discussed the underlying factors that are driving the economics of intelligent systems. Discover how hardware commoditization, the ubiquitous nature of connectivity, and the emergence of Big Data a...

ARMONK, N.Y., Nov. 20, 2014 /PRNewswire/ --  IBM (NYSE: IBM) today announced that it is bringing a greater level of control, security and flexibility to cloud-based application development and delivery with a single-tenant version of Bluemix, IBM's platform-as-a-service. The new platform enables developers to build ap...

SYS-CON Events announced today that IDenticard will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. IDenticard™ is the security division of Brady Corp (NYSE: BRC), a $1.5 billion manufacturer of identification products. We have small-company values with the strength and stability of a major corporation. IDenticard offers local sales, support and service to our customers across the United States and Canada. Our partner network encompasses some 300 of the world's leading systems integrators and security s...
DevOps Summit 2015 New York, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that it is now accepting Keynote Proposals. The widespread success of cloud computing is driving the DevOps revolution in enterprise IT. Now as never before, development teams must communicate and collaborate in a dynamic, 24/7/365 environment. There is no time to wait for long development cycles that produce software that is obsolete at launch. DevOps may be disruptive, but it is essential.
"People are a lot more knowledgeable about APIs now. There are two types of people who work with APIs - IT people who want to use APIs for something internal and the product managers who want to do something outside APIs for people to connect to them," explained Roberto Medrano, Executive Vice President at SOA Software, in this SYS-CON.tv interview at Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
Nigeria has the largest economy in Africa, at more than US$500 billion, and ranks 23rd in the world. A recent re-evaluation of Nigeria's true economic size doubled the previous estimate, and brought it well ahead of South Africa, which is a member (unlike Nigeria) of the G20 club for political as well as economic reasons. Nigeria's economy can be said to be quite diverse from one point of view, but heavily dependent on oil and gas at the same time. Oil and natural gas account for about 15% of Nigera's overall economy, but traditionally represent more than 90% of the country's exports and as...
The Internet of Things is a misnomer. That implies that everything is on the Internet, and that simply should not be - especially for things that are blurring the line between medical devices that stimulate like a pacemaker and quantified self-sensors like a pedometer or pulse tracker. The mesh of things that we manage must be segmented into zones of trust for sensing data, transmitting data, receiving command and control administrative changes, and peer-to-peer mesh messaging. In his session at @ThingsExpo, Ryan Bagnulo, Solution Architect / Software Engineer at SOA Software, focused on desi...
"At our booth we are showing how to provide trust in the Internet of Things. Trust is where everything starts to become secure and trustworthy. Now with the scaling of the Internet of Things it becomes an interesting question – I've heard numbers from 200 billion devices next year up to a trillion in the next 10 to 15 years," explained Johannes Lintzen, Vice President of Sales at Utimaco, in this SYS-CON.tv interview at @ThingsExpo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
"For over 25 years we have been working with a lot of enterprise customers and we have seen how companies create applications. And now that we have moved to cloud computing, mobile, social and the Internet of Things, we see that the market needs a new way of creating applications," stated Jesse Shiah, CEO, President and Co-Founder of AgilePoint Inc., in this SYS-CON.tv interview at 15th Cloud Expo, held Nov 4–6, 2014, at the Santa Clara Convention Center in Santa Clara, CA.
SYS-CON Events announced today that Gridstore™, the leader in hyper-converged infrastructure purpose-built to optimize Microsoft workloads, will exhibit at SYS-CON's 16th International Cloud Expo®, which will take place on June 9-11, 2015, at the Javits Center in New York City, NY. Gridstore™ is the leader in hyper-converged infrastructure purpose-built for Microsoft workloads and designed to accelerate applications in virtualized environments. Gridstore’s hyper-converged infrastructure is the industry’s first all flash version of HyperConverged Appliances that include both compute and storag...
Today’s enterprise is being driven by disruptive competitive and human capital requirements to provide enterprise application access through not only desktops, but also mobile devices. To retrofit existing programs across all these devices using traditional programming methods is very costly and time consuming – often prohibitively so. In his session at @ThingsExpo, Jesse Shiah, CEO, President, and Co-Founder of AgilePoint Inc., discussed how you can create applications that run on all mobile devices as well as laptops and desktops using a visual drag-and-drop application – and eForms-buildi...
We certainly live in interesting technological times. And no more interesting than the current competing IoT standards for connectivity. Various standards bodies, approaches, and ecosystems are vying for mindshare and positioning for a competitive edge. It is clear that when the dust settles, we will have new protocols, evolved protocols, that will change the way we interact with devices and infrastructure. We will also have evolved web protocols, like HTTP/2, that will be changing the very core of our infrastructures. At the same time, we have old approaches made new again like micro-services...
Code Halos - aka "digital fingerprints" - are the key organizing principle to understand a) how dumb things become smart and b) how to monetize this dynamic. In his session at @ThingsExpo, Robert Brown, AVP, Center for the Future of Work at Cognizant Technology Solutions, outlined research, analysis and recommendations from his recently published book on this phenomena on the way leading edge organizations like GE and Disney are unlocking the Internet of Things opportunity and what steps your organization should be taking to position itself for the next platform of digital competition.
The 3rd International Internet of @ThingsExpo, co-located with the 16th International Cloud Expo - to be held June 9-11, 2015, at the Javits Center in New York City, NY - announces that its Call for Papers is now open. The Internet of Things (IoT) is the biggest idea since the creation of the Worldwide Web more than 20 years ago.
As the Internet of Things unfolds, mobile and wearable devices are blurring the line between physical and digital, integrating ever more closely with our interests, our routines, our daily lives. Contextual computing and smart, sensor-equipped spaces bring the potential to walk through a world that recognizes us and responds accordingly. We become continuous transmitters and receivers of data. In his session at @ThingsExpo, Andrew Bolwell, Director of Innovation for HP's Printing and Personal Systems Group, discussed how key attributes of mobile technology – touch input, sensors, social, and ...