Tuesday, 5 May 2015

Externalizable vs Serializable

  • Externalizable is an interface that enables you to define custom rules and your own mechanism for serialization. Serializable defines standard protocol and provides out of the box serialization capabilities.
  • Externalizable extends Serializable.
  • Implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization.
  • Saving the state of the supertypes is responsibility of the implementing class.
  • You might have seen in my previouse article on how to customize the default implementation of Serializable. These two methods readExternal and writeExternal (Externalizable) supersedes this customized implementation of readObject and writeObject.
  • In object de-serialization (reconsturction) the public no-argument constructor is used to reconstruct the object. In case of Serializable, instead of using constructor, the object is re-consturcted using data read from ObjectInputStream.
  • The above point subsequently mandates that the Externalizable object must have a public no-argument constructor. In the case of Seriablizable it is not mandatory.
  • Behaviour of writeReplace and readResolve methods are same for both Serializable and Externalizable objects. writeReplace allows to nominate a replacement object to be written to the stream. readResolve method allows to designate a replacement object for the object just read from the stream.
  • In most real time scenarios, you can use Serializable and write your own custom implementation for serialization by providing readObject and writeObject.
  • You may need Externalizable,
    1. If you are not happy with the way java writes/reads objects from stream.
    2. Special handling for supertypes on object construction during serialization.

No comments: