The java.io.Externalizable Interface

Objects that implement the java.io.Externalizable interface can also have their state saved and restored. When an object is encountered during the serialization process, it is examined to see if it implements java.io.Serializable. If it doesn’t, it is examined to see if it implements java.io.Externalizable. Externalizable objects are in complete control of their own serialization. There is no default mechanism for saving or restoring their state. The object’s writeExternal() method is called when the object is being saved, and its readExternal() method is called when it is being restored.

The class hierarchy will not be walked for objects that implement java.io. Externalizable. It is up to the object to make sure that data from any superclasses gets serialized since it isn’t handled automatically. Versioning is also the responsibility of the object itself. The object serialization mechanism reads and writes the class definition of the object, and then turns the rest of the process over to the object.

Let’s look at an example with a three-level hierarchy, similar to the example used previously. Class CC is a subclass of class BB, which is a subclass of class AA. Since class AA implements java.io.Externalizable, all of its subclasses are externalizable as well. Each class implements the writeExternal() and readExternal() methods. The code for these classes is shown here:

class AA implements java.io.Externalizable { protected int a = 0; public ...

Get Developing Java Beans 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.