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 writeObject( ) method of the ObjectOutputStream class and deserialized by the readObject( ) method of the ObjectInputStream class. These classes are byte streams like the various other streams we saw in Chapter 3. They implement the ObjectOutput and ObjectInput interfaces, respectively, and these interfaces extend the DataOutput and DataInput interfaces. This means that ObjectOutputStream defines the same methods as DataOutputStream for writing primitive values, 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 serialized. 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 ...

Get Java Examples in a Nutshell, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.