Java Reference
In-Depth Information
Listing 6-3.
An Externalizable Version of DVD.java: Implementing the readExternal and
writeExternal Methods of DVD.java
/**
* Required method for Externalizable interface.
* Specifies how the object graph gets converted to a byte stream.
*/
private void writeExternal(ObjectOutput out) throws IOException{
out.writeUTF(upc);
out.writeUTF(name);
out.writeUTF(composer);
out.writeUTF(director);
out.writeUTF(leadActor);
out.writeUTF(supportingActor);
out.writeUTF(year);
out.writeInt(copy);
}
/**
* Required method for Externalizable interface.
* Specifies how to recreate the object graph from
* a byte stream. The order members are read must
* match the order in which the object members were
* written to the stream.
*/
private void readExternal(ObjectInput in) throws IOException{
out.readUTF(upc);
out.readUTF(name);
out.readUTF(composer);
out.readUTF(director);
out.readUTF(leadActor);
out.readUTF(supportingActor);
out.readUTF(year);
out.readInt(copy);
}
■
Caution
As was the case with
persistDVD
and
retrieveDVD
, the
readExternal
and
writeExternal
methods are not included in the actual project code base, but are used merely as a pedagogical device for
demonstrating externalization.
Since
Externalizable
is considered a more advanced serialization approach, we will
not cover
Externalizable
any further in this topic. Rather, we have chosen to implement
Serializable
for simplicity, but
Externalizable
is mentioned so that you understand the
alternative.
Serializable
is simpler to implement but sacrifices performance and flexibility.