Java Reference
In-Depth Information
This output reveals a thrown instance of the
InvalidClassException
class.
This exception object was thrown during deserialization because
Employee
doesn't
possess a noargument constructor.
Wecanovercomethisproblembytakingadvantageofthewrapperclasspatternthat
Ipresentedin
Chapter2
.Furthermore,wedeclareapairofprivatemethodsinthesub-
class that the serialization and deserialization mechanisms look for and call.
Normally, the serialization mechanism writes out a class's instance fields to the un-
derlying output stream. However, you can prevent this from happening by declaring
a private
void writeObject(ObjectOutputStream oos)
method in that
class.
Whentheserializationmechanismdiscoversthismethod,itcallsthemethodinstead
of automatically outputting instance field values. The only values that are output are
those explicitly output via the method.
Conversely,thedeserializationmechanismassignsvaluestoaclass'sinstancefields
thatitreadsfromtheunderlyinginputstream.However,youcanpreventthisfromhap-
peningbydeclaringaprivate
void readObject(ObjectInputStream ois)
method.
When the deserialization mechanism discovers this method, it calls the method in-
stead of automatically assigning values to instance fields. The only values that are as-
signed to instance fields are those explicitly assigned via the method.
Because
SerEmployee
doesn't introduce any fields, and because
Employee
doesn'tofferaccesstoitsinternalfields(assumeyoudon'thavethesourcecodeforthis
class), what would a serialized
SerEmployee
object include?
Althoughwecannotserialize
Employee
'sinternal state, wecanserialize theargu-
ment(s) passed to its constructors, such as the employee name.
classes.
Listing 8-17.
Solving problematic deserialization
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;