Java Reference
In-Depth Information
Suppose you have a file containing objects that represent employees. The basic characteristics of all em-
ployees are defined in a base class, Person , but various different types of employee are represented by sub-
classes of Person . You might have subclasses Manager , Secretary , Admin , and ShopFloor , for example.
The file can contain any of the subclass types in any sequence. Of course, you can cast any object read from
the file to type Person because that is the base class, but you want to know precisely what each object is so
you can call some type-specific methods. Because you know what the possible types are, you can check the
type of the object against each of these types and cast accordingly:
Person person = null;
try ( ... ){
Person person = (Person)objectIn.readObject();
if(person instanceof Manager)
processManager((Manager)person);
else if(person instanceof Secretary)
processSecretary((Secretary)person);
// and so on...
} catch (IOException e){
e.printStackTrace();
}
Here you determine the specific class type of the object read from the file before calling a method that
deals with that particular type of object. Don't forget though that the instanceof operator does not guaran-
tee that the object being tested is actually of the type tested for — Manager , say. The object could also be of
any type that is a subclass of Manager . In any event, the cast to type Manager is perfectly legal.
Where you need to be absolutely certain of the type, you can use a different approach:
String className = person.getClass().getName();
if(className.equals("Manager"))
processManager((Manager)person);
else if(className.equals(Secretary))
processSecretary((Secretary)person);
// and so on...
This calls the getClass() method (inherited from Object ) for the object that was read from the file and
that returns a reference to the Class object that represents the class of the object. Calling the getName()
method for the Class object returns the fully qualified name of the class. This approach guarantees that the
object is of the type for which you are testing, and is not a subclass of that type.
Another approach would be to just execute a cast to a particular type, and catch the ClassCastException
that is thrown when the cast is invalid. This is fine if you do not expect the exception to be thrown under
normal conditions, but if on a regular basis the object read from the stream might be other than the type to
which you are casting, you are much better off with code that avoids the need to throw and catch the excep-
tion because this adds quite a lot of overhead.
Reading Basic Data from an Object Stream
The ObjectInputStream class defines the methods that are declared in the DataInput interface for reading
basic types of data back from an object stream and binary values. They are:
Search WWH ::




Custom Search