在Java中将对象的临时成员反序列化为非null的默认值
问题内容:
public class MyObj implements Serializable {
private transient Map<String, Object> myHash = new HashMap<String, Object>();
...
}
有什么方法可以确保当对上述类的对象进行反序列化时,成员myHash将被设置为新的空Map,而不是被设置为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>();
}
}