Lecture 12: Object Serialization

Overview

Java provides a method for writing an Object to an output stream and reading the Object back into memory. If the the target of the output stream is a file, then we have object persistance: a way of freezing an object in time and coming back to it later. If the target is a socket, then we have network objects: a way of sending entire objects from one place on the net to another.

Examples

The details

To be serialized, an object must implement the java.io.Serializable interface. If not, during serialization, the object's fields will not be written out.

If an object references other objects, then these objects will also be serialized with the object. In this way, a single call to serialization will write an entire web of objects. Each object is written just once, however, by a technique called serialization (which is where the process gets its name). Each object is given a serial number as it is written. If the serializer encounters an object with a serial number higher than that of the root object for this current serialization, than it has already been writen has a dependant of the root of this current serialization, and it is not written again.

The java.io.ObjectOutputStream class extends java.io.OutputStream by adding the ability to write Java data types, including Objects. Note that java.io.DataOutputStream does not have a method for writing objects, indicating that it is not capable of doing so. Likewise, The java.io.ObjectInputStream class extends java.io.InputStream by adding the ability to read Java data types, including Objects.

Casting must be used to read an object, since the type of the object returned is a generic object. Various exceptions can be thrown, including java.lang.ClassNotFoundException, which indicates that the input stream was presented the task of deserializing a class for which it does not have a description.