According to Serializable javadoc, readResolve()
is intended for replacing an object read from the stream. But surely (?) you don't have to replace the object, so is it OK to use it for restoring transient fields and return the original reference, like so:
private Object readResolve() {
transientField = something;
return this;
}
as opposed to using readObject()
:
private void readObject(ObjectInputStream s) {
s.defaultReadObject();
transientField = something;
}
Is there any reason to choose one over other, when used to just restore transient fields? Actually I'm leaning toward readResolve()
because it needs no parameters and so it could be easily used also when constructing the objects "normally", in the constructor like:
class MyObject {
MyObject() {
readResolve();
}
...
}