Name

ObjectOutputStream

Synopsis

The ObjectOutputStream serializes objects, arrays, and other values to a stream. The writeObject( ) method serializes an object or array, and various other methods write primitive data values to the stream. Note that only objects that implement the Serializable or Externalizable interface can be serialized.

A class that wants to customize the way instances are serialized should declare a private writeObject(ObjectOutputStream) method. This method is invoked when an object is being serialized and can use several additional methods of ObjectOutputStream. defaultWriteObject( ) performs the same serialization that would happen if no writeObject( ) method existed. An object can call this method to serialize itself and then use other methods of ObjectOutputStream to write additional data to the serialization stream. The class must define a matching readObject( ) method to read that additional data, of course. When working with multiple versions or implementations of a class, you may have to serialize a set of fields that do not precisely match the fields of your class. In this case, give your class a static field named serialPersistentFields whose value is an array of ObjectStreamField objects that describe the fields to be serialized. In your writeObject( ) method, call putFields( ) to obtain an ObjectOutputStream.PutField object. Store field names and values into this object, and then call writeFields( ) to write them out to the serialization stream. ...

Get Java in a Nutshell, 5th Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.