Right way to reinitialise transient variable

Assume a simple serializable Object like this:

public class MySerializable implements Serializable{
    String value;
    transient String test = "default";

    public MySerializable() {
        test = "init";
    }
}

If an instance of this is serialized and unserialized, the variable test still is null. My approach would be to write a new method like this:

private String getTest(){
    test = test==null?"default":test;
    return test;
}

And call this everytime the test variable is called.

Is there a better (more beautiful) solution?

Jon Skeet
people
quotationmark

From the docs for Serializable:

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void writeObject(java.io.ObjectOutputStream out)
    throws IOException
private void readObject(java.io.ObjectInputStream in)
    throws IOException, ClassNotFoundException;
private void readObjectNoData()
    throws ObjectStreamException;

[...]

The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object's non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

So basically, I think you want:

public class MySerializable implements Serializable{
    String value;
    transient String test = "default";

    public MySerializable() {
        test = "init";
    }

    private void readObject(java.io.ObjectInputStream in)
         throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        test = "init";
    }
}

people

See more on this question at Stackoverflow