【问题标题】:My global variable value is not being preserved after deserialization反序列化后我的全局变量值没有被保留
【发布时间】: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


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    为了扩展answer of Mattdefault Java serialization 将序列化非瞬态和非静态变量。序列化的目的是能够从流中恢复对象的状态。由于静态变量不是这个类的状态,而是系统的状态,所以它没有被序列化。

    请注意,通过实现 readObjectwriteObject 方法来序列化静态是可能的,但可能并不明智。

    Java™ Object Serialization specification 对此的描述比您可能关心的更详细;-)

    【讨论】:

    • 能够恢复对象的状态
    猜你喜欢
    • 2018-12-11
    • 2014-08-23
    • 2011-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-06-01
    • 1970-01-01
    • 1970-01-01
    • 2021-06-10
    相关资源
    最近更新 更多