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

前端 未结 3 1720
误落风尘
误落风尘 2020-12-14 18:05
public class MyObj implements Serializable {
  private transient Map myHash = new HashMap();
  ...
}

Is

相关标签:
3条回答
  • 2020-12-14 18:14
    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>();
        }
    }
    
    0 讨论(0)
  • 2020-12-14 18:28

    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.

    0 讨论(0)
  • 2020-12-14 18:32

    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 讨论(0)
提交回复
热议问题