Search code examples
javaserializationexternalizable

Serializable and Externalizable. Difference of constructor invocation while deserialization


I have read following article:

http://javapapers.com/core-java/externalizable-vs-serializable/

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.

Is it truth about constructor invocation that

Serializable:
While deserialization invokes constructor of nearest non Serializable ancestor only

Externalizable:
While deserialization invokes constructor of class which implements Externalizable interface only.

?


Solution

  • Yes, In byte code you can create an instance of a object and call any constructor in the hierarchy. In truth, a constructor is a special method and it is even call it more than once.

    Many deserializers just use Unsafe.allocateInstance() and don't call any constructors. This is done to minimise side effects when deserializing.