Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

need of defaultReadObject() and defaultWriteObject()

Why it's needed to write defaultReadObject() and defaultWriteObject() as the first statement in readObject(ObjectInputStream o) and writeObject(ObjectOutputStream o) methods when a class implements serializable interface.


2 Answers

defaultReadObject() and defaultWriteObject() should be the first method call inside readObject(ObjectInputStream o) and writeObject(ObjectOutputStream o). It reads and writes all the non transient fields of the class respectively. These methods also helps in backward and future compatibility. If in future you add some non-transient field to the class and you are trying to deserialize it by the older version of class then the defaultReadObject() method will neglect the newly added field, similarly if you deserialize the old serialized object by the new version then the new non transient field will take default value from JVM i.e. if its object then null else if primitive then boolean to false, int to 0 etc….

like image 94
Trying Avatar answered Dec 30 '25 16:12

Trying


Here some useful lines from the Docs

defaultReadObject() method read the non-static and non-transient fields of the current class from this stream.

And as same for the writing too.

like image 33
Suresh Atta Avatar answered Dec 30 '25 17:12

Suresh Atta



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!