從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啊..當然是肯定的 - 即使沒有它的實例類本身仍然加載。哦,是的 - 所以現在它非常有意義。非常感謝! :-) –