从6 SCJP学习指南 - 有询问关于序列化下面的代码的输出问题:
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原值,或不能以正常方式被创建的类,类默认整型值0,而不是保持与它的非反序列化后-Default 10递增的值? 我本来以为是10的值会丢失,但这种情况并非如此。
任何人一些启发? 我跌跌撞撞在这里在黑暗中磕碰在这一个我的脚趾..