Java Reference
In-Depth Information
Figure 16.8
Sample output of the PipeDemo program.
An Overview of Serialization
One of the most impressive features of the Java language is its built-in use of
serialization. Serialization refers to the process of saving the state of an object
by sending it to an output stream, and deserialization is the process of retriev-
ing the object back into memory. Most impressive is that the entire process is
JVM independent, meaning an object can be serialized on one platform and
deserialized on an entirely different platform.
Java practically trivializes the process of serialization because the JVM does
most of the work for you. The ObjectOutputStream and ObjectInputStream
classes are high-level streams that contain the methods for serializing and dese-
rializing an object. The ObjectOutputStream class contains many write methods
for writing various data types, but one method in particular stands out:
public final void writeObject(Object x) throws IOException
This method serializes an Object and sends it to the output stream. Similarly,
the ObjectInputStream class contains the following method for deserializing
an object:
public final Object readObject() throws IOException, ClassNotFoundException
This method retrieves the next Object out of the stream and deserializes it. The
return value is Object, so you will need to cast it to its appropriate data type.
Classroom Q & A
Q: What exactly does the writeObject() method send to the output
stream?
A: The purpose of serialization is to save the state of an Object. If you
think about it, the state of an Object that makes it unique is the
value of its fields. The writeObject() method, among other infor-
mation, sends the values of the object's fields to the output stream.
Search WWH ::




Custom Search