According to Serializable javadoc, readResolve() intended to replace an object read from a stream. But, of course, (?) You donβt need to replace the object, so itβs normal to use it to restore temporary fields and return the original link, for example:
private Object readResolve() { transientField = something; return this; }
unlike using readObject() :
private void readObject(ObjectInputStream s) { s.defaultReadObject(); transientField = something; }
Is there any reason to choose one over the other when used only to restore transition fields? In fact, I tend to readResolve() , because it does not need parameters, and therefore it can be easily used also when building objects βusuallyβ in the constructor, for example:
class MyObject { MyObject() { readResolve(); } ... }
java serialization transient
Joonas pulakka
source share