静态类变量和序列化/反序列化
从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(++sz + " "); 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()语句中将对象写入文件后,static int变量z的值增加到10。
在这种情况下,为什么在反序列化时不返回它的原始值9,或者没有以正常方式创建类,类默认int值为0,而不是保留为非反序列化后-default递增值为10? 我原本以为10的价值会丢失,但实际情况并非如此。
有人放光了吗? 我在黑暗中磕磕绊绊地盯着我的脚趾。
基本上,实例是序列化的,而不是类。 该类声明的任何静态字段不受该类实例的序列化/反序列化的影响。 要将z
重置为9
,需要重新加载 SpecialSerial
类,这是另一回事。
s2.z
的值是SpecialSerial
类的静态成员z
的SpecialSerial
,这就是它保持为10的原因SpecialSerial
类的限制,而不是实例。
就好像你已经这样做了
++SpecialSerial.z System.out.println(SpecialSerial.z)
代替
++sz System.out.println(s2.z)