静态类变量和序列化/反序列化 [英] static class variables and serialization / deserialization

查看:303
本文介绍了静态类变量和序列化/反序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在SCJP 6学习指南中-有一个问题要求输出以下有关序列化的代码:

From the SCJP 6 study guide - there is a question asking for the output of the following code regarding serialization:

import java.io.*;

public class TestClass {
  static public void main(String[] args) {
    SpecialSerial s = new SpecialSerial();
    try {
        ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myFile"));
        os.writeObject(s);
        os.close();
        System.out.print(++s.z + " ");
        s = null;  // makes no difference whether this is here or not

        ObjectInputStream is = new ObjectInputStream(new FileInputStream("myFile"));
        SpecialSerial s2 = (SpecialSerial)is.readObject();
        is.close();
        System.out.println(s2.y + " " + s2.z);
    } catch (Exception e) {e.printStackTrace();}
  }
}
class SpecialSerial implements Serializable {
    transient int y = 7;
    static int z = 9;
}

此输出为:10 0 10

The output of this is: 10 0 10

给出的原因是静态变量z没有序列化,我不会期望它是序列化的。

The reason given for this is that the static variable z is not serialized, which I would not have expected it to be.

在将对象写入文件后,在println()语句中,静态int变量z的值将增加为10。

The value of the static int variable z is incremented to 10 after the object has been written to file, in the println() statement.

是这种情况,为什么在反序列化该类时它为什么不返回到其原始值9,或者由于未按正常方式创建该类,所以该类的默认int值是0,而不是在反序列化后保留非默认的10增量值?我本来以为10的值会丢失,但事实并非如此。

This being the case, why is it not back to either it's original value of 9 when the class is deserialized, or as the class is not being created in the normal way, the class default int value of 0, rather than remaining with it's non-default incremented value of 10 after deserialization? I would have thought the value of it being 10 would be lost, but this is not the case.

有人能说清楚吗?我在这里徘徊,脚趾踩在黑暗中。

Anyone shed some light? I'm stumbling around here in the dark stubbing my toes on this one..

推荐答案

基本上,实例是序列化的,而不是类。该类声明的任何静态字段都不受该类实例的序列化/反序列化的影响。对于将 z 重置为 9 SpecialSerial 类需要重新加载,这是另一回事

Basically, instances are serialized, not classes. Any static fields declared by the class are unaffected by serialization/deserialization of an instance of the class. For z to be reset to 9, the SpecialSerial class would need to be reloaded, which is a different matter.

这篇关于静态类变量和序列化/反序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆