【发布时间】:2013-12-19 22:04:44
【问题描述】:
我像这样序列化了一个名为 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 serialization deserialization