ITEM 88: WRITE READOBJECT METHODS DEFENSIVELY
355
The
byte
array literal used to initialize
serializedForm
was generated by
serializing a normal
Period
instance and hand-editing the resulting byte stream.
The details of the stream
are unimportant to the example, but if you’re curious, the
serialization byte-stream format is described in the
Java Object Serialization
Specification
[Serialization, 6]. If you run this program,
it prints
Fri
Jan
01
12:00:00
PST
1999
-
Sun
Jan
01
12:00:00
PST
1984
. Simply declaring
Period
serializable enabled us to create an object that violates its class invariants.
To fix this problem, provide a
readObject
method for
Period
that calls
defaultReadObject
and then checks the validity of the deserialized object. If the
validity check fails, the
readObject
method
throws
InvalidObjectException
,
preventing the deserialization from completing:
Do'stlaringiz bilan baham: