Java Reference
In-Depth Information
If the class is not found or cannot be loaded for any reason, readObject
will throw a ClassNotFoundException .
20.8.4. Customized Serialization
The default serialization methods work for many classes but not for all
of them. For some classes default deserialization may be improper or in-
efficient. The HashMap class is an example of both problems. Default seri-
alization would write all the data structures for the hash map, including
the hash codes of the entries. This serialization is both wrong and inef-
ficient.
It is wrong because hash codes may be different for deserialized entries.
This will be true, for example, of entries using the default hashCode im-
plementation.
It is inefficient because a hash map typically has a significant number of
empty buckets. There is no point in serializing empty buckets. It would
be more efficient to serialize the referenced keys and entries and rebuild
a hash map from them than to serialize the entire data structure of the
map.
For these reasons, java.util.HashMap provides private writeObject and
readObject methods. [3] These methods are invoked by ObjectOutputStream
and ObjectInputStream , respectively, when it is time to serialize or deseri-
alize a HashMap object. These methods are invoked only on classes that
provide them, and the methods are responsible only for the class's own
state, including any state from non-serializable superclasses. A class's
writeObject and readObject methods, if provided, should not invoke the
superclass's readObject or writeObject method. Object serialization differs
in this way from clone and finalize .
[3] These methods are private because they should never be overridden and they should never be
invoked by anyone using or subclassing your class. The serialization mechanism gains access to
these private methods using reflection to disable the language level access control (see page 426 ) . Of
course this can only happen if the current security policy allows itsee " Security " on page 677 .
 
 
Search WWH ::




Custom Search