Java 反序列化后未保留我的全局变量值
我序列化了一个名为GreenhouseControls的类,如下所示:Java 反序列化后未保留我的全局变量值,java,serialization,deserialization,Java,Serialization,Deserialization,我序列化了一个名为GreenhouseControls的类,如下所示: public class GreenhouseControls extends Controller implements Serializable{ ...... public void saveState() { try{ // Serialize data object to a file ObjectOutputStream o
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) {
}
}
......
}
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();
}
}
}
......
}
序列化GreenhouseControls对象时,全局静态变量“errorcode”设置为1
然后我反序列化了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) {
}
}
......
}
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();
}
}
}
......
}
当我在反序列化后将“errorcode”打印到console时,我期望值为1,但打印的却是0,变量的默认值。反序列化后是否应保留静态变量序列化时的值 否,静态变量不会序列化,因为它们独立于要序列化的实例化对象而存在。要展开,将序列化非瞬态和非静态的变量。序列化的目的是能够从流中恢复对象的状态。由于静态变量不是此类的状态,而是系统的状态,所以它不是序列化的 注意,通过实现和方法序列化静态是可能的,但可能不是明智的
描述这一点的详细程度超出了您可能关心的范围;-) 请参见,以便能够恢复对象的状态。