Java Reference
In-Depth Information
The following method could be added to the Message class to reject a serialized object
that has an empty from value:
private void readObject(ObjectInputStream ois)
throws IOException, ClassNotFoundException {
ois.defaultReadObject();
if (from.length() < 1) {
throw new IOException(“Null sender in message.”);
}
}
16
Inspecting Classes and Methods with
Reflection
On Day 3, “Working with Objects,” you learned how to create Class objects that repre-
sent the class to which an object belongs. Every object in Java inherits the getClass()
method, which identifies the class or interface of that object. The following statement
creates a Class object named keyclass from an object referred to by the variable key :
Class keyClass = key.getClass();
By calling the getName() method of a Class object, you can find out the name of the
class:
String keyName = keyClass.getName();
These features are part of Java's support for reflection , a technique that enables one Java
class—such as a program you write—to learn details about any other class.
Through reflection, a Java program can load a class it knows nothing about; find the vari-
ables, methods, and constructors of that class; and work with them.
One use of reflection is to determine a serialized object's class when it is read.
Inspecting and Creating Classes
The Class class, which is part of the java.lang package, is used to learn about and cre-
ate classes, interfaces, and even primitive types.
In addition to using getClass() , you can create Class objects by appending .class to
the name of a class, interface, array, or primitive type, as in the following examples:
Class keyClass = KeyClass.class;
Class thr = Throwable.class;
Class floater = float.class;
Class floatArray = float[].class;
 
Search WWH ::




Custom Search