views:

167

answers:

1

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

    ...
}
+1  A: 

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.

Riduidel
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.
Joonas Pulakka
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.
Riduidel