Chapter 17

Java Serialization

Imagine a building that, with a push of a button, can be turned into a pile of construction materials and the possessions of its residents. Push another button and the building is re-created in its original form in a different location. This is what Java serialization is about. By “pushing the serialize button” you turn an instance of an object into a pile of bytes, and “pushing the deserialize button” magically re-creates the object.

Wikipedia defines the term serialization as

the process of converting a data structure or object into a sequence of bits so that it can be stored in a file or memory buffer, or transmitted across a network connection link to be “resurrected” later in the same or another computer environment. When the resulting series of bits is reread according to the serialization format, it can be used to create a semantically identical clone of the original object… This process of serializing an object is also called deflating or marshalling an object. The opposite operation, extracting a data structure from a series of bytes, is deserialization (which is also called inflating or unmarshalling).

In Lesson 16 you became familiar with streams that deal with single bytes, characters, Java primitives, and text. Now you’ll see why and how to write objects into streams, or how to serialize Java objects.

Consider the following scenario: ClassA creates an instance of the object Employee, which has the fields firstName, lastName, address ...

Get Java® Programming 24-Hour Trainer 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.