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.
- 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,
- If you are not happy with the way java writes/reads objects from stream.
- Special handling for supertypes on object construction during serialization.
There's another reason to use externalizable: if you expect your code to evolve, then you may be reading back your stored data using a different implementation of the class than the one that wrote it. With serializable, you need to be sure that all the members you need line up properly. With Externalizable, you can handle the interop any way you want.
ReplyDelete(I helped design Externalizable many years ago.)
Thanks Noah....
ReplyDelete