Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

readObject() vs. readResolve() to restore transient fields

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

    ...
}
like image 789
Joonas Pulakka Avatar asked May 10 '10 08:05

Joonas Pulakka


2 Answers

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.

like image 89
Riduidel Avatar answered Oct 13 '22 18:10

Riduidel


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.

like image 28
Jason C Avatar answered Oct 13 '22 18:10

Jason C