Serialization
Using a
DataOutputStream, you could write an application
that saves the data content of an arbitrary object as simple types.
However Java provides an even more powerful mechanism called
object serialization that does almost all of the
work for you. In its simplest form, object serialization is an
automatic way to save and load the state of an object. However,
object serialization has depths that we cannot plumb within the scope
of this book, including complete control over the serialization
process and interesting conundrums like class versioning.
Basically, an object of any class
that implements the Serializable interface can be
saved and restored from a stream. Special stream
subclasses,
ObjectInputStream
and
ObjectOutputStream
, are used to serialize primitive types
and objects. Subclasses of Serializable classes
are also serializable. The default serialization mechanism saves the
value of an object’s nonstatic and nontransient (see the
following explanation) member variables.
One of the most important (and tricky) things about serialization is
that when an object is serialized, any object references it contains
are also serialized. Serialization can capture entire
“graphs” of interconnected objects and put them back
together on the receiving end (we’ll demonstrate this in an
upcoming example). The implication is that any object we serialize
must contain only references to other Serializable objects. We can take control by marking nonserializable members as ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access