Java Reference
In-Depth Information
CHAPTER 9
Object Serialization
Object serialization is the ability of a
Serializable
class to output the state of an
object instance to a byte stream and, at some later time, read that state back in,
creating a copy of the original object. When an object is serialized, the entire
object graph of all the objects it refers to are serialized along with it. This means
it's possible to serialize complex data structures such as binary trees. It's also pos-
sible to serialize applets and complete GUI component hierarchies.
Simple Serialization
Despite the power and importance of serialization, it is performed using a simple
API that forms part of the
java.io
package: an object is serialized by the
write-
Object()
method of the
ObjectOutputStream
class and deserialized by the
read-
Object()
method of the
ObjectInputStream
class. These classes are byte streams
like the various other streams we saw in Chapter 3,
Input/Output
. They implement
the
ObjectOutput
and
ObjectInput
interfaces, respectively, and these interfaces
extend the
DataOutput
and
DataInput
interfaces. This means that
ObjectOutput-
Stream
defines the same methods as
DataOutputStream
for writing primitive val-
ues, while
ObjectInputStream
defines the same methods as
DataInputStream
for
reading primitive values. The methods we're interested in here, however, are
writeObject()
and
readObject()
, which write and read objects.
Only objects that implement the
java.io.Serializable
interface may be serial-
ized.
Serializable
is a marker interface; it doesn't define any methods that need
to be implemented. Nevertheless, for security reasons, some classes don't want
their private state to be exposed by the serialization mechanism. Therefore, a class
must explicitly declare itself to be serializable by implementing this interface.
An object is serialized by passing it to the
writeObject()
method of an
ObjectOutputStream
. This writes out the values of all of its fields, including private
fields and fields inherited from superclasses. The values of primitive fields are sim-
ply written to the stream as they would be with a
DataOutputStream
. When a field
in an object refers to another object, an array, or a string, however, the
write-
Object()
method is invoked recursively to serialize that object as well. If that