JAVA的序列化問題

今天工做時發現一個序列化的問題:java

基類(類A)沒有實現序列化接口(Serializable),而子類(類B)實現了序列化接口,對子類對像進行序列化,而後反序列化,這裏發現反序化後的對象在基類的中的不少屬性都變成了null.
  
  
           
  
  
  1. public abstract class FirstLevel {//基類  
  2.     private Map map;  
  3.    
  4.     public FirstLevel(){  
  5.      System.out.println("first");  
  6.     }  
  7.     protected void init(){  
  8.        map = new HashMap(0);  
  9.     }  
  10.       
  11.     public Map getMap() {  
  12.        return map;  
  13.     }  
  14.     public void setMap(Map map) {  
  15.        this.map = map;  
  16.     }  
  17. }  
  18.    
  19. public class SecondLevel extends FirstLevel implements Serializable{  
  20.     public SecondLevel(){  
  21.        init();  
  22.        System.out.println("second");  
  23.     }  
  24. }  
  25.    
  26. public class Test {  
  27.     public static void main(String args[]) throws FileNotFoundException, IOException, ClassNotFoundException{  
  28.        System.out.println("before:");  
  29.        SecondLevel before = new SecondLevel();  
  30.        HashMap a = new HashMap();  
  31.        a.put("key""guojje");  
  32.        before.setMap(a);   
  33.          
  34.        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("c:\\t.txt"));  
  35.        oos.writeObject(before);  
  36.        oos.close();  
  37.        System.out.println("after:");  
  38.        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("c:\\t.txt"));  
  39.        SecondLevel after = (SecondLevel)ois.readObject();  
  40.        ois.close();  
  41.        System.out.println(after.getMap());  
  42.          
  43.     }  
  44. }  
 
 
輸出:
before:
first
second
after:
first
null
這裏map屬性我是賦過值的,爲何變成NULL了嗎,另外建立對像時調用FirstLevel ,
SecondLevel 兩個構造函數,可是反序列化時也調用了FirstLevel的構造函數(理論上序列化是不用調用構造函數的)。
 
看來沒有實現序列化接口的基類並無真正的序列化與反序列化,而是借用其構造函數來實現對象的初始化(能夠確定得不到序列化時的屬性值),由於FirstLevel的構造函數並無初始化MAP成員,因此返回NULL。
 
查閱一些資料,JDK文檔上這麼說:
序列化操做不會寫出沒有實現 java.io.Serializable 接口的任何對象的字段。不可序列化的 Object 的子類能夠是可序列化的。在此狀況下,不可序列化的類必須有一個無參數構造方法,以便容許初始化其字段。在此狀況下,子類負責保存和還原不可序列化的類的狀態。
 
果真如此。
 
又一個問題(A>B表示B繼承於A):
   A > B (Serializable)> C > D(Serializable) > E
反序列化E對象,會調用哪幾個構造函數呢,答案是一個, A的. 由於其餘類都從基類繼承了Serializable接口,而A沒有.
 
下一個問題,若是想徹底的序列化E對象怎麼辦:
在子類中(B,C,D,E均可)來序例化A類的成員,而後賦值上去,別無他法.
相關文章
相關標籤/搜索