Discovering Information at Run Time
By Bruce Eckel
Over the next couple of months, I'll look at the two ways that Java allows you to discover information about objects and classes at run time: traditional run-time type information (RTTI) mechanism, which assumes you have all the types available at compile time and run time; and the "reflection" mechanism in Java 1.1, which allows you to discover class information solely at run time.
Run-time type identification seems fairly simple at first. It lets you find the exact type of an object when you have only a handle to the base type. However, the need for RTTI uncovers a plethora of interesting object-oriented design issues, and raises fundamental questions about program structure.
The Need for RTTI
Consider a class hierarchy that uses polymorphism. The generic type is the base class shape, and the specific derived types are circle, square, and triangle; see
Figure 1.
Normally in object-oriented programming, the bulk of your code manipulates handles to the base type (shape, in this case), so if you extend the program by adding a new class (rhomboid, derived from shape, for example), most of the code is not affected. In this example, the dynamically bound function in the shape interface is draw(), so the client programmer would call draw() through a generic shape handle.