Friday, 4 February 2011

The Serializable and Externalizable Iterfaces

The difference between Serializable and Externalizable interfaces and when to use each one...
public interface Externalizable extends Serializable
Externalization is similar to Serialize except that an object is responsible for saving its own state using methods calls:
void readExternal(ObjectInput in)
The object implements the readExternal method to restore its contents by calling the methods of DataInput for primitive types and readObject for objects, strings and arrays.
void writeExternal(ObjectOutput out)
The object implements the writeExternal method to save its contents by calling the methods of DataOutput for its primitive values or calling the writeObject method of ObjectOutput for objects, strings, and arrays.

This method of persisting an object supersedes the readObject() and writeObject() methods from ObjectInputStream and ObjectOutputStream used by Serialization.

An object using externalization is also responsible for orchestrating the externalization of its super classes.

Use externalisation when an object requires advanced control over the way that they are written and read, for example a word processor object may want to externalize itself using its own file format.

No comments: