ʞɔıu ʞɔıu - 2 months ago 14
Java Question

Deserialize a transient member of an object to a non-null default in Java

public class MyObj implements Serializable {
private transient Map<String, Object> myHash = new HashMap<String, Object>();
...
}


Is there any way to ensure that when an object of the above class is deserialized the member myHash will be set to a new empty Map rather than be set to null?

Answer
public class MyObj implements Serializable {
    private transient Map<String, Object> myHash = new HashMap<String, Object>();

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();

        myHash = new HashMap<String, Object>();
    }
}
Comments