Externalizable Classes
The Externalizable
interface extends Serializable
and
defines the writeExternal( )
and
readExternal( )
methods. An
Externalizable
object may be
serialized as other Serializable
objects are, but the serialization mechanism calls writeExternal( )
and readExternal( )
to perform the serialization
and deserialization. Unlike the readObject(
)
and writeObject( )
methods in Example 10-2, the
readExternal( )
and writeExternal( )
methods can’t call the
defaultReadObject( )
and defaultWriteObject( )
methods: they must
read and write the complete state of the object by themselves.
It is useful to declare an object Externalizable
when the object already has
an existing file format or when you want to accomplish something that
is simply not possible with the standard serialization methods. Example 10-3 defines the CompactIntList
class, an Externalizable
subclass of the IntList
class of Example 2-7. CompactIntList
makes the assumption that it
is typically used to store small integers that fit in two bytes
instead of four; it implements Externalizable
so it can define a serialized
form that is more compact than the format used by ObjectOutputStream
and ObjectInputStream
.
Example 10-3. CompactIntList.java
package je3.serialization; import je3.classes.IntList; import java.io.*; /** * This subclass of IntList assumes that most of the integers it contains are * less than 32,000. It implements Externalizable so that it can define a * compact serialization format that takes ...
Get Java Examples in a Nutshell, 3rd Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.