Class-Specific Serialization
Sometimes
the data members that are marked as transient are
an important part of the run-time state of the object. Consider a
class that maintains an instance of a
java.io.FileOutputStream, a class that cannot be
serialized because it uses a file handle. It would be dangerous to
save the handle because it is allocated at run-time, and the objects
may be reconstructed on another system that uses a different scheme
for allocating file handles. Also, if the file handle were to be
saved it could be modified to resemble a handle that is not normally
accessible. This would be a security violation, and could even result
in unwanted or malicious behavior. Nevertheless, when the object is
reconstructed, we would want to reestablish the instance of the
java.io.FileOutputStream. We might handle this by
saving the name of the file along with the current value of the seek
offset.
It is possible to extend the default serialization behavior. Any
class that implements java.io.Serializable can
implement its own
writeObject()
and
readObject()
methods for this purpose.
If you want the serialization mechanism to ask your object to write
its own data, it should provide a writeObject()
method with the following signature:
private void writeObject(ObjectOutputStream stream)
throws java.io.IOException;If this method exists, the data members will not automatically be
serialized. It is up to the writeObject() method to store the state of the object. However, it doesn’t need ...
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