从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()语句中将对象写入文件后,static int变量z的值会递增为10。
既然如此,为什么当这个类被反序列化或者因为类没有以正常方式创建时,它的原始值不是9,而是类的默认int值为0,而不是在反序列化之后,它的非默认递增值是10吗?我会认为它的价值将会丢失,但事实并非如此。
任何人都会发光?我在这里磕磕绊绊在这个黑暗的脚趾上。
Aaahh啊..当然是肯定的 - 即使没有它的实例类本身仍然加载。哦,是的 - 所以现在它非常有意义。非常感谢! :-) –