2014-11-25 112 views
0

似乎是一個奇怪的問題,但是看看這個簡單的代碼:我應該在java中重寫readObject()writeObject()多少?

public class Father implements Serializable{ 
    private static final long serialVersionUID = 1L; 
    String familyName = "Josepnic"; 
    String name = "Gabriel" 
    void writeObject (ObjectOutputStream out) throws IOException{ 
     out.writeObject(familyName); 
     out.writeObject(name); 
    } 
    void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 
     familyName = (String) in.readObject(); 
     name = (String) in.readObject(); 
    } 
} 
public class Child extends Father{ 
    private static final long serialVersionUID = 1L; 
    String name = "Josep"; 
    void writeObject (ObjectOutputStream out) throws IOException{ 
     out.writeObject(name); 
    } 
    void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 
     name = (String) in.readObject(); 
    } 
} 

我不知道,如果孩子也應該WIRTE父親的姓,或者它會自動寫入? (我這樣說是因爲父親有一個writeObject(),itselsf但我不知道Java序列化的處理)。

也許一個很好的建議是

public class Child extends Father{ 
    private static final long serialVersionUID = 1L; 
    String name = "Josep"; 
    @Override 
    void writeObject (ObjectOutputStream out) throws IOException{ 
     super.writeObject(out); 
     out.writeObject(name); 
    } 
    @Override 
    void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 
     super.readObject(in); 
     name = (String) in.readObject(); 
    } 
} 
+1

爲什麼你首先寫這些方法?你爲什麼不測試它? – 2014-11-25 12:54:28

+1

由於這是一個常見問題,我想在網絡上爲其他人搜索它 – hossayni 2014-11-25 12:55:08

+0

正如你所看到的,我自己已經在 – hossayni 2014-11-25 12:55:39

回答

1
void writeObject (ObjectOutputStream out) throws IOException{ 
    out.writeObject(familyName); 
    out.writeObject(name); 
} 
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 
    familyName = (String) in.readObject(); 
    name = (String) in.readObject(); 
} 

void writeObject (ObjectOutputStream out) throws IOException{ 
    out.writeObject(name); 
} 
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { 
    name = (String) in.readObject(); 
} 

它不會在最不管你把張貼,因爲他們都不是以往任何時候都稱這些方法。根據對象序列化規範的要求,它們不是private,所以序列化不會調用它們。

而且考慮到他們應該是私人的,使用@Override也是徒勞的。

由於您的代碼可能有效,您可以從中得出結論,您根本不需要這樣做。讓序列化爲你做。

相關問題