Custom Methods JavaBeans: Interaction with Components
Ivan Marsic • Rutgers University
256
A simple way to solve this problem is to check for all possible objects using instanceof, the operator that lets you test at run-time, whether or not an object is of a given type. A more
advanced way is supported by the java.lang.reflect package, which lets you find out almost anything you want to know about an object’s class at run-time.
An important class for reflection is the class Class, which at first may sound confusing. Each instance of the class Class encapsulates the information about a particular class or interface.
There is one such object for each class or interface loaded into the JVM.
There are two ways to get an instance of class Class from within a running program: 1.
Ask for it by name using the static method forName: Class fooClass = Class.forNameFoo;
This method will return the Class object that describes the class Foo 2.
Ask an instance of any Object for its class: Foo f = new Foo;
Class fooClass = f.getClass; As a side note, this construct is legal:
Class classClass = Class.forNameClass; It returns back the instance of Class that describes the class Class.
Once you have a Class object, you can call methods on it to find out information about the class. None of the methods are mutators, so you cannot change the class at run-time. However,
you can use it to create new instance of a class, and to call methods on any instance. Some of the methods available in class Class are:
Constructor getConstructorClass[] paramTypes; Constructor[] getConstructors;
Field getFieldString name; Field[] getFields;
Method getMethodString name, Class[] paramTypes; Method[] getMethods;
boolean isInstanceObject obj; boolean isPrimitive;
String getName;
Chapter 7 • Software
Components 257
String toString; The return types Constructor, Field, and Method are defined in the package
java.lang.reflect .