Java Reference
In-Depth Information
Figure 8-6.
The
serialver
GUI reveals
Employee
's SUID.
Custom Serialization and Deserialization
Mypreviousdiscussionfocusedondefaultserializationanddeserialization(withtheex-
ceptionofmarkinganinstancefield
transient
topreventitfrombeingincludeddur-
ing serialization). However, situations arise where you need to customize these tasks.
For example, suppose you want to serialize instances of a class that doesn't imple-
ment
Serializable
.Asaworkaround,yousubclassthisotherclass,havethesub-
classimplement
Serializable
,andforwardsubclassconstructorcallstothesuper-
class.
Althoughthisworkaroundletsyouserializesubclassobjects,youcannotdeserialize
these serialized objects when the superclass doesn't declare a noargument constructor,
which is required by the deserialization mechanism.
Listing 8-16
demonstrates this
problem.
Listing 8-16.
Problematic deserialization
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
class Employee
{
private String name;
Employee(String name) { this.name = name; }
@Override
public String toString() { return name; }
}
class SerEmployee extends Employee implements Serializable