gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 21:12:20 25 4
gpt4 key购买 nike

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com