To initialize a transient field, what is the most simple solution

扶醉桌前 提交于 2019-12-29 16:29:08

问题


class MyClass implements Serializable {
  transient int myTransient;
  //Other variables
}

When I restore this class I want to initialize myTransient manually, but otherwise I just want to use the default serialization.

How can I inject an init() method into the object restore process without re-writing the entire serialization mechanism as it seems like Externalizable would have me do?


回答1:


Implement a readObject() method:

private void readObject(java.io.ObjectInputStream in)
    throws IOException, ClassNotFoundException {
    in.defaultReadObject();
    myTransient = ...;
}

From javadoc:

Classes that require special handling during the serialization and deserialization process must implement special methods with these exact signatures:

private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException;

The readObject method is responsible for reading from the stream and restoring the classes fields. It may call in.defaultReadObject to invoke the default mechanism for restoring the object's non-static and non-transient fields. The defaultReadObject method uses information in the stream to assign the fields of the object saved in the stream with the correspondingly named fields in the current object. This handles the case when the class has evolved to add new fields. The method does not need to concern itself with the state belonging to its superclasses or subclasses. State is saved by writing the individual fields to the ObjectOutputStream using the writeObject method or by using the methods for primitive data types supported by DataOutput.

See also:

  • Serializable javadoc


来源:https://stackoverflow.com/questions/3960546/to-initialize-a-transient-field-what-is-the-most-simple-solution

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!