O'Reilly logo

Java Examples in a Nutshell, 3rd Edition by David Flanagan

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required