在Java中将对象的临时成员反序列化为非null默认值 [英] Deserialize a transient member of an object to a non-null default in Java

查看:256
本文介绍了在Java中将对象的临时成员反序列化为非null默认值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

有什么方法可以确保对上面类的对象进行反序列化,将成员myHash设置为新的空Map而不是设置为null?

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

这篇关于在Java中将对象的临时成员反序列化为非null默认值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆