Java Reference
In-Depth Information
Object Serialization and Deserialization
Javaprovidesthe
DataOutputStream
and
DataInputStream
classestostream
primitive type values and
String
objects. However, you cannot use these classes to
streamnon-
String
objects.Instead,youmustuseobjectserializationanddeserializa-
tion to stream objects of arbitrary types.
Object serialization
isaJVMmechanismfor
serializing
objectstateintoastreamof
bytes. Its
deserialization
counterpart is a JVM mechanism for
deserializing
this state
from a byte stream.
Note
An object's state consists of instance fields that store primitive type values
and/orreferencestootherobjects.Whenanobjectisserialized,theobjectsthatarepart
of this state are also serialized (unless you prevent them from being serialized), their
objects are serialized unless prevented, and so on.
Javasupportsthreeformsofserializationanddeserialization:defaultserializationand
deserialization, custom serialization and deserialization, and externalization.
Default Serialization and Deserialization
Defaultserializationanddeserializationistheeasiestformtousebutofferslittlecontrol
over how objects are serialized and deserialized. Although Java handles most of the
work on your behalf, there are a couple of tasks that you must perform.
Your first task is to have the class of the object that's to be serialized implement
the
java.io.Serializable
interface(directly,orindirectlyviatheclass'ssuper-
class).Therationaleforimplementing
Serializable
istoavoidunlimitedserializa-
tion.
Note
Serializable
is an empty marker interface (there are no methods to
implement) that a class implements to tell the JVM that it's okay to serialize the
class's objects. When the serialization mechanism encounters an object whose class
doesn't implement
Serializable
, it throws an instance of the
java.io.NotSerializableException
class (an indirect subclass of
IOEx-
ception
).
Unlimited serialization
istheprocessofserializinganentire
object graph
(allobjects
that are reachable from a starting object). Java doesn't support unlimited serialization
for the following reasons:
•
Security
:IfJavaautomaticallyserializedanobjectcontainingsensitiveinform-
ation(suchasapasswordoracreditcardnumber),itwouldbeeasyforahacker