我經歷系列化,我不明白以下幾點:Java序列行爲
我不明白爲什麼這個代碼的輸出是:
import java.io.*;
public class InnerOuterTest {
public static ObjectOutputStream out;
public static ObjectInputStream in;
static {
try {
out = new ObjectOutputStream(new FileOutputStream("save.ser"));
in = new ObjectInputStream(new FileInputStream("save.ser"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws IOException, ClassNotFoundException {
try {
ShouldForgive f = new ShouldForgive();
f.x = 5;
write(f);
ShouldForgive g = read();
System.out.println(g.x);
f.x = 0;
g.x=8;
write(f);
ShouldForgive v = read();
System.out.println("is "+v.x);
} finally {
out.close();
in.close();
}
}
private static void write(ShouldForgive f) throws IOException {
out.writeObject(f);
}
public static ShouldForgive read() throws ClassNotFoundException, IOException {
return (ShouldForgive) in.readObject();
}
}
class ShouldForgive implements Serializable {
int x = -1;
}
是
5
8
而且不
5
0
我試過f == g
,它返回false,如果我重置輸入流。我發現如果我執行readObject
它只被調用一次...我不明白這種行爲。 (爲什麼對象只能讀取一次?)
我覺得序列化只發生一次......對象是如何跟蹤的?即使我實現readObject
和writeObject
而不實際讀取或從文件寫入我仍然得到8
不安靜。如果它們是兩個不同的對象,如何寫入「f」寫入值「8」? – kosa
不是它正在打印8,而是5 ...嘗試我編輯的部分 –
如果對象寫得很好,那麼哈希碼很可能是相同的。 – EJP