[ Java ] Externalizable Vs. Serializable

♠ Posted by GeekyFry in ,,, at 6:57 AM

Externalizable Vs. Serializable   

  1. 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.
  2. Externalizable extends Serializable.
  3. Implement writeExternal and readExternal methods of the Externalizable interface and create your own contract / protocol for serialization.
  4. Saving the state of the supertypes is responsibility of the implementing class.
  5. You might have seen in my previouse article on how tocustomize the default implementation of Serializable. These two methods readExternal and writeExternal (Externalizable) supersedes this customized implementation of readObject and writeObject.
  6. 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.
  7. 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.
  8. 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.
  9. In most real time scenarios, you can use Serializable and write your own custom implementation for serialization by providing readObject and writeObject.
You might need to use 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.


Post a Comment