Java Reference
In-Depth Information
se object read from file
John Doe
The
writeObject()
and
readObject()
methods can be used to serialize/
deserialize data items beyond the normal state (non-
transient
instance fields); for
example, serializing/deserializing the contents of a
static
field.
However, before serializing or deserializing the additional data items, you must tell
the serialization and deserialization mechanisms to serialize or deserialize the object's
normal state. The following methods help you accomplish this task:
•
ObjectOutputStream
's
defaultWriteObject()
methodoutputsthe
object's normal state. Your
writeObject()
method first calls this method
to output that state, and then outputs additional data items via
ObjectOut-
putStream
methods such as
writeUTF()
.
•
ObjectInputStream
's
defaultReadObject()
methodinputstheob-
ject's normal state. Your
readObject()
method first calls this method to
input that state, and then inputs additional data items via
ObjectIn-
putStream
methods such as
readUTF()
.
Externalization
Alongwithdefaultserialization/deserializationandcustomserialization/deserialization,
Java supports externalization. Unlike default/custom serialization/deserialization,
ex-
ternalization
offers complete control over the serialization and deserialization tasks.
Note
Externalization helps you improve the performance of the reflection-based
serializationanddeserializationmechanismsbygivingyoucompletecontroloverwhat
fields are serialized and deserialized.
Javasupportsexternalizationviaits
java.io.Externalizable
interface.This
interface declares the following pair of
public
methods:
•
void writeExternal(ObjectOutput out)
savesthecallingobject's
contents by calling various methods on the
out
object. This method throws
IOException
when an I/O error occurs. (
java.io.ObjectOutput
is
a subinterface of
DataOutput
and is implemented by
ObjectOut-
putStream
.)
•
void readExternal(ObjectInput in)
restores the calling object's
contents by calling various methods on the
in
object. This method throws
IOException
when an I/O error occurs, and
ClassNotFoundExcep-