Reputation: 37078
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.
?
Upvotes: 1
Views: 206
Reputation: 672
Deserialization process in case of Externalizable interface depend on passed constructor and we explicitly create its object but in case of Serializable interface, object get created by ObjectStreamClass.newInstance(). So there is no role of constructor here.
After that, it internally store an array of data/objects(any custom field, string, int ...etc) which is linked with passed inputStream object. All array elements (which store state of object) later set into the object and it will return to system.
Also i would like to inform you that there is no mandatory to have no-arg constructor in case of Externalizable. We can create object by passing all the arguments as null during constructor initialization and that would work fine.
ExternalizablePair1 copyOfPair = new ExternalizablePair1(null,null,null);
FileInputStream inputStream = new FileInputStream(OUTPUT_FILE);
ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
copyOfPair.readExternal(objectInputStream);
@Override
public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
this.key = in.readUTF();
this.value = in.readUTF();
this.emp = (Employee) in.readObject();
}
Upvotes: 1
Reputation: 533680
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.
Upvotes: 1