gpt4 book ai didi

java - 反序列化后我的全局变量值没有被保留

转载 作者:行者123 更新时间:2023-12-01 07:28:27 26 4
gpt4 key购买 nike

我像这样序列化了一个名为 GreenhouseControls 的类:

public class GreenhouseControls extends Controller implements Serializable{

......

public void saveState() {
try{
// Serialize data object to a file
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("dump.out"));
out.writeObject(GreenhouseControls.this);
System.out.println(GreenhouseControls.errorcode); // Prints 1
out.close();
} catch (IOException e) {
}
}

......

}

当 GreenhouseControls 对象被序列化时,全局静态变量“errorcode”被设置为 1。

然后我反序列化了 GreenhouseControls 类,如下所示:

public class GreenhouseControls extends Controller implements Serializable{

......

public class Restore extends Event {

.....

@Override
public void action() {
try {

FileInputStream fis = new FileInputStream(eventsFile);
ObjectInputStream ois = new ObjectInputStream(fis);
GreenhouseControls gc = (GreenhouseControls) ois.readObject();
System.out.println("Saved errorcode: " + gc.errorcode); // Prints 0 (the default value)
ois.close();
}catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}

......

}

当我在反序列化后将“错误代码”打印到控制台时,我期待的是 1 值,但打印的是 0(变量的默认值)。静态变量序列化时的值在反序列化后是否应该保留?

最佳答案

不,静态变量不会被序列化,因为它们独立于您要序列化的实例化对象而存在。

关于java - 反序列化后我的全局变量值没有被保留,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20692586/

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