August 28, 2014
Hot Topics:
RSS RSS feed Download our iPhone app

Java Reflection in Action

  • May 11, 2005
  • By Dr. Ira Forman & Nate Forman
  • Send Email »
  • More Articles »

1.4 Finding a method at runtime

At the beginning of our example, George's setObjectColor method is passed a parameter obj of type Object. The method cannot do any introspection until it knows the class of that parameter. Therefore, its first step is to query for the parameter's class:

Class cls = obj.getClass();

The getClass method is used to access an object's class at runtime. The getClass method is often used to begin reflective programming because many reflective tasks require objects representing classes. The getClass method is introduced by java.lang.Object, so any object in Java can be queried for its class1.

The getClass method returns an instance of java.lang.Class. Instances of Class are the metaobjects that Java uses to represent the classes that make up a program. Throughout this book, we use the term class object to mean an instance of java.lang.Class. Class objects are the most important kind of metaobject because all Java programs consist solely of classes.

Class objects provide programming metadata about a class's fields, methods, constructors, and nested classes. Class objects also provide information about the inheritance hierarchy and provide access to reflective facilities. For this chapter, we will concentrate on the use of Class in listing 1 and related fundamentals.

Once the setObjectColor method has discovered the class of its parameter, it queries that class for the method it wants to call:

Method method = cls.getMethod("setColor", new Class[] {Color.class});

The first parameter to this query is a String containing the desired method's name, in this case, setColor. The second parameter is an array of class objects that identify the types of the method's parameters. In this case, we want a method that accepts one parameter of type Color, so we pass getMethod an array of one element containing the class object for Color.

Notice that the assignment does not use getClass to provide the class object for Color. The getClass method is useful for obtaining the class for an object reference, but when we know only the name of the class, we need another way. Class literals are Java's way to specify a class object statically. Syntactically, any class name followed by .class evaluates to a class object. In the example, George knows that setObjectColor always wants a method that takes one Color argument. He specifies this using Color.class.

Class has other methods for introspecting about methods. The signatures and return types for these methods are shown in table 1.1. As in the previous example, the queries use an array of Class to indicate the types of the parameters. In querying for a parameterless method, it is legal to supply null, which is treated the same as a zero-length array.

Table 1.1 The methods defined by Class for method query

Method Description
Method getMethod ( String name,
                   Class[] parameterTypes )
Returns a Method object that represents a public method (either declared or inherited) of the target Class object with the signature specified by the second parameters
Method[] getMethods ()
Returns an array of Method objects that represent all of the public methods (either declared or inherited) supported by the target Class object
Method getDeclaredMethod (
                 String name,
                 Class[] parameterTypes )
Returns a Method object that represents a declared method of the target Class object with the signature specified by the second parameters
Method[] getDeclaredMethods ()
Returns an array of Method objects that represent all of the methods declared by the target Classobject

As their names indicate, getDeclaredMethod and getDeclaredMethods return method objects for methods explicitly declared by a class. The set of declared methods does not include methods that the class inherits. However, these two queries do return methods of all visibilities—public, protected, package, and private.

The queries getMethod and getMethods return method objects for a class's public methods. The set of methods covered by these two includes both methods declared by the class and those it inherits from superclasses. However, these queries return only a class's public methods.

A programmer querying a class using getDeclaredMethod might accidentally specify a method that the class does not declare. In this case, the query fails with a NoSuchMethodException. The same exception is thrown when getMethod fails to find a method among a class's public methods.

In the example, George needs to find a method, and he does so using one of the methods from table 1.1. Once retrieved, these method objects are used to access information about methods and even call them. We discuss method objects in detail later in this chapter, but first let's take a closer look at how class objects are used with the methods from table 1.1.

End Notes

1 The getClass method is final. This keeps Java programmers from fooling reflective programs. If it were not final, a programmer could override getClass to return the wrong class.

More to Come

The rest of this material will appear on our website starting May 25th.

About the Authors

Dr. Ira Forman is a senior software engineer at IBM. He started working on reflection in the early 1990s when he developed IBM's SOM Metaclass Framework. Nate Forman works for Ticom Geomatics where he uses reflection in day-to-day problems. Ira and Nate are father and son. They live in Austin, Texas.

About the Book

Java Reflection in Action By Ira R. Forman and Nate Forman


Published October 2004, Softbound, 300 pages
Published by Manning Publications Co.
ISBN 1932394184
Retail price: $44.95
Ebook price: $22.50. To purchase the ebook go to http://www.manning.com/forman.
This material is from Chapter 1 of the book.



Page 3 of 3



Comment and Contribute

 


(Maximum characters: 1200). You have characters left.

 

 


Sitemap | Contact Us

Rocket Fuel