java - 要初始化 transient 字段,最简单的解决方案是什么

标签 java serialization

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

当我恢复这个类时,我想手动初始化 myTransient,否则我只想使用默认的序列化。

我怎样才能将 init() 方法注入(inject)到对象恢复过程中,而无需像 Externalizable 那样重写整个序列化机制?

最佳答案

实现一个readObject()方法:

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

来自 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.

另请参阅:

关于java - 要初始化 transient 字段,最简单的解决方案是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3960546/

相关文章:

java - 单击按钮时修改变量/其他 Swing 对象

java - 为什么 Java 中除负零会返回正无穷大?

c# - 为什么简单类型的序列化如此复杂?

ruby-on-rails - 对 Rails 序列化器数据进行排序

Java 反序列化数组列表时所有值为 null

java - Play-java 2.5.9 form.errorsAsJson() 总是返回英文错误信息

java - 一个响应中可以设置多少个 cookie?

java - Android 中使用 BaseAdapter 的 GridView?

javascript - 从 GWT RPC 负载中反序列化日期和时间戳以进行调试

c# - 序列化/反序列化和非默认构造函数