7

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

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

给出的原因是静态变量 z 没有序列化,这是我没想到的。

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

既然如此,为什么当类被反序列化时它没有回到它的原始值 9,或者由于没有以正常方式创建类,类默认 int 值 0,而不是保持它的非- 反序列化后的默认增量值为 10?我原以为它是 10 的值会丢失,但事实并非如此。

有人阐明了吗?我在黑暗中跌跌撞撞地在这附近绊倒我的脚趾..

4

2 回答 2

3

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

于 2012-11-11T23:50:20.587 回答
2

The value of s2.z is the value of a static member z of SpecialSerial class, that's why it stays 10. z is bounded by the class, and not the instance.

It's as if you've done this

++SpecialSerial.z
System.out.println(SpecialSerial.z)

instead of

++s.z
System.out.println(s2.z)
于 2012-11-11T23:51:53.447 回答