开发者

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

开发者 https://www.devze.com 2023-02-06 18:58 出处:网络
public class MyObj implements Serializable { private transient Map<String, Object> myHash = new HashM开发者_高级运维ap<String, Object>();
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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号