ReadObject () vs. readResolve () to restore transition fields

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(); } ... } 
+7
java serialization transient
source share
2 answers

In fact, readResolve has been defined to give you greater control over how objects are deserialized. As a result, you are free to do whatever you want (including setting a value for the transition field).

However, I suppose your transient field is set with a constant value. Elsewhere, it would be a sure sign that something is wrong: either your field is not temporary, or your data model is based on false assumptions.

+4
source share

Use readResolve. The readObject method allows you to configure how the object is read if the format is different from the expected default value. This is not what you are trying to do. The readResolve method, as its name implies, refers to resolving an object after reading it, and its purpose is to allow you to resolve the state of an object that does not recover after deserialization. This is what you are trying to do. You can return "this" from readResolve.

+4
source share

All Articles