readObject() vs. readResolve() to restore transient fields
Asked Answered
S

2

7

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();
    }

    ...
}
Silvia answered 10/5, 2010 at 8:11 Comment(0)
D
4

In fact, readResolve has been define to provide you higher control on the way objects are deserialized. As a consequence, you're left free to do whatever you want (including setting a value for an transient field).

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

Desex answered 10/5, 2010 at 8:19 Comment(2)
Actually the field is not a constant value, it's a Map for quick lookup from a List (which is the canonical representation). No need to store the same thing twice. Of course the Map could also be lazily created when first time needed; not much difference.Silvia
Well, OK. In fact, I was mostly suggesting that there could be a design flaw hidden. However, you explaination is clear, and in this case readResolve will do the trick without any doubt.Desex
H
4

Use readResolve. The readObject method lets you customize how the object is read, if the format is different than the expected default. This is not what you are trying to do. The readResolve method, as its name implies, is for resolving the object after it is read, and its purpose is precisely to let you resolve object state that is not restored after deserialization. This is what you are trying to do. You may return "this" from readResolve.

Howland answered 20/11, 2011 at 13:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.