Java Reference
In-Depth Information
Serializing Objects
In this chapter, we will see how you can transfer objects to and from a stream. By the end of this chapter
you will have learned:
What serialization is and how you make a class serializable.
❑
How to write objects to a file.
❑
What transient fields in a class are.
❑
How to write basic types of data to an object file.
❑
How to implement the
Serializable
interface.
❑
How to read objects from a file.
❑
How to implement serialization for classes containing objects that are not serializable by default.
❑
Storing Objects in a File
The process of storing and retrieving objects in an external file is called
serialization
. Note that an array
of any type is an object for the purposes of serialization, even an array of values of a primitive type,
such as type
int
or type
double
. Writing an object to a file is referred to as
serializing
the object, and
reading an object from a file is called
deserializing
an object. Serialization is concerned with writing
objects and the fields they contain to a stream, so this excludes
static
members of a class. Static fields
will have whatever values are assigned by default in the class definition.
I think you will be surprised at how easy this is. Perhaps the most impressive aspect of the way
serialization is implemented in Java is that you can generally read and write objects of almost any class
type, including objects of classes that you have defined yourself, without adding any code to the classes
involved to support this mechanism. For the most part, everything is taken care of automatically: