gpt4 book ai didi

java - 重新初始化 transient 变量的正确方法

转载 作者:行者123 更新时间:2023-11-30 07:13:56 26 4
gpt4 key购买 nike

假设一个简单的可序列化对象如下:

public class MySerializable implements Serializable{
String value;
transient String test = "default";

public MySerializable() {
test = "init";
}
}

如果 this 的一个实例被序列化和反序列化,变量 test 仍然是 null。我的方法是编写一个像这样的新方法:

private String getTest(){
test = test==null?"default":test;
return test;
}

每次调用 test 变量时调用它。

有没有更好(更漂亮)的方案?

最佳答案

来自 Serializable 的文档:

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

private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException;
private void readObjectNoData()
throws ObjectStreamException;

[...]

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.

所以基本上,我想你想要:

public class MySerializable implements Serializable{
    String value;
    transient String test = "default";

    public MySerializable() {
        test = "init";
    }

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

关于java - 重新初始化 transient 变量的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18893032/

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