2012-06-29 20 views
-3

我經歷系列化,我不明白以下幾點: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它只被調用一次...我不明白這種行爲。 (爲什麼對象只能讀取一次?)

我覺得序列化只發生一次......對象是如何跟蹤的?即使我實現readObjectwriteObject而不實際讀取或從文件寫入我仍然得到8

回答

2

如果你第一次寫後打電話out.reset(),你會得到你期待的行爲,或者如果您使用writeUnshared()代替writeObject()。已經寫入流的對象不會被重寫;而是寫入先前寫入的對象的「句柄」。有關詳細信息,請參閱Javadoc。

-1

OK ...我想我懂了......

  1. 在系列化,其NOT該對象被序列化,但其實例變量...被提取並存儲。對於一個對象其實例變量是一切...

    反序列化期間
  2. 所以,相同實例變量被充氣背部,以及使用那些 實例變量值,上所創建的另一個相同的對象堆..

  3. 如果你檢查這兩個對象的哈希碼,它們將會不同。

這就是導致你提到的上述行爲。

要麼按照此序列

f.x = 0; 
g.x=8; 

或該

g.x=8;  
f.x = 0; 

儘管如此,結果將是8時,使得對不同的實例變量的堆其現在完全不同的對象。

編輯部分

The below code will print f as 5..... for both the sysout

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; 
      write(f); 
      ShouldForgive v = read(); 
      System.out.println("is "+v.x); 
     } finally { 
      out.close(); 
      in.close(); 
     } 
    } 
+0

不安靜。如果它們是兩個不同的對象,如何寫入「f」寫入值「8」? – kosa

+0

不是它正在打印8,而是5 ...嘗試我編輯的部分 –

+0

如果對象寫得很好,那麼哈希碼很可能是相同的。 – EJP