反序列化后,我的全局变量值未被保留

Loo*_*nin 0 java serialization deserialization

我像这样序列化了一个名为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) {
              }
      }

 ......

}
Run Code Online (Sandbox Code Playgroud)

当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();
              } 
          }
      }

......

}
Run Code Online (Sandbox Code Playgroud)

当我在反序列化后将"错误代码"打印到控制台时,我期望得到1值,而不是0,即打印变量的默认值.反序列化后是否应保留静态变量序列化时的值?

Mat*_*ngs 5

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