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 HashM开发者_高级运维ap<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?
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>();
}
}
What about adding a readObject method like this:
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>();
}
}
That should sort you out.
You can implement your own custom readIn
method and explicitly create a new Map<T>
as explained in the Java Serializable documentation. That article should describe how to do what you're looking for; check the section entitled Customize the Default Protocol.
精彩评论