java 要初始化一个瞬态字段,最简单的解决方案是什么

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3960546/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-30 04:09:52  来源:igfitidea点击:

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

javaserialization

提问by David Parks

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

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

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

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

如何init()在不重写整个序列化机制的情况下将方法注入对象还原过程,就像Externalizable我应该做的那样?

回答by axtavt

Implement a readObject()method:

实现一个readObject()方法:

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

From javadoc:

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

在序列化和反序列化过程中需要特殊处理的类必须实现具有以下确切签名的特殊方法:

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

readObject 方法负责从流中读取并恢复类字段。它可以调用 in.defaultReadObject 来调用默认机制来恢复对象的非静态和非瞬态字段。defaultReadObject 方法使用流中的信息将保存在流中的对象的字段分配给当前对象中相应命名的字段。这可以处理类已经演变为添加新字段的情况。该方法不需要关心属于它的超类或子类的状态。通过使用 writeObject 方法或使用 DataOutput 支持的原始数据类型的方法将各个字段写入 ObjectOutputStream 来保存状态。

See also:

也可以看看: