Java Reference
In-Depth Information
Figure 6-3. Running the serialver tool on the DVD class
Figure 6-4. Running the serialver tool on the DvdFileAccess class
Since we started serialver from the DennyDVD classes directory, we can inspect our proj-
ect's classes for the Serializable interface. If we had started from another directory, we would
have had to make sure that our project was listed in our system classpath. Inspecting our
classes for the Serializable interface is not very interesting since we have the source
code and are well aware which classes are Serializable and which are not (i.e., we can simply
inspect the file visually to see if Serializable is implemented). But using serialver on classes
in which we do not have source code is much more useful—for instance, classes in a JAR file
or classes that are part of the JDK.
For fun, try inspecting other classes in your classpath, such as those in the Java JDK
(i.e., java.util.Date or java.lang.String ).
If you inspect the source code for both the DVD and DVDFileAccess classes (downloadable
from http://www.apress.com ), you will note that DVD does indeed implement Serializable ,
while DVDFileAccess does not.
The Serialization Process
To actually persist an object's state, there are two classes in the java.io package that perform
the bulk of work required for reading and writing serializable objects: ObjectOutputStream
and ObjectInputStream . ObjectOutputStream has a method called writeObject , while
ObjectInputStream has a method called readObject . In the Denny's DVDs project, serialization
is used to send method parameters across the network between the GUI and the server using
the default serialization mechanism (e.g., whether the server is an RMI or a socket server). We
do not actually serialize our method parameters explicitly for RMI to work. In fact, our only
concern is that the object sent across the network be serializable. Let's assume that we want
to persist the state of our DVD objects explicitly to the file system. In that case, we could do
so by implementing the persistDVD and retrieveDVD methods. When the client wants to save
the state of a database record or DVD object, such as after a setRecordNumber call, the client
invokes the DVDFileAccess method persistDVD . persistDVD serializes the DVD object using the
ObjectOutputStream class and its writeObject method. The persistDVD method is shown in
Listing 6-1. Keep in mind that the actual member we are serializing is a DVD. Our DVD class
must be Serializable . The retrieveDVD method reads the serialized object and re-creates the
object, as demonstrated in Listing 6-2.
Search WWH ::




Custom Search