2015-04-02 64 views
0

我有一個有很多信息的類Bucket,其中我只想將(可串行化的)兩個字段存儲到一個文件中。因此,我做了Bucket擴展ChatData它只保留這兩個字段,因爲我認爲當上傳時,我可能會丟失無用的信息,然後將bucket對象存儲爲chatdata對象。向父類丟失信息 - 存儲對象的一部分

但是,上傳到超類不會使對象失去其子類信息。我怎樣才能做到這一點?

public class ChatData implements Serializable { 
    private int f1 = 1; 
    private int f2 = 2; 
} 

public class Bucket extends ChatData implements Serializable { 
    private int f3 = 3; 
    private int f4 = 4; // useless data when it comes to storing 
    private int f5 = 5; 
    public void store(ObjectOutputStream oos) { 
     oos.writeObject((ChatData) this); // does also store f3, f4, f5, 
     // ... but I don't whant these! 
     // also, unnecessary cast, does not do anything 
    } 

    public static void main(String[] args) { 
     Bucket b = new Bucket(); 
     b.store(new ObjectOutputStream(new FileOutputStream("C:/output.dat")); 
    } 
} 

(未經測試的代碼,只爲可視化)

我怎麼能寫我Bucket對象作爲ChatData對象到我的硬盤驅動器?如果不是,只有部分存儲對象的首選方法是什麼?

我能想到一個簡單的解決方案,比如創建一個全新的對象,但我寧願理解什麼是最好的方法。

回答

1

如果你不想序列化一個類的成員。只需將其標記爲transient即可。

在你的特殊情況下,你不需要經歷創建超類的麻煩。做到這一點,而不是:

public class Bucket implements Serializable { 
    transient private int f3 = 3; 
    transient private int f4 = 4; // useless data when it comes to storing 
    transient private int f5 = 5; 
    private int f1 = 1; 
    private int f2 = 2; 

    //leave the remaining code in this class as it is 
} 
+0

這在某種程度上也幾乎沒有任何節省硬盤空間可言,雖然一半的數據應該是失蹤......不知道爲什麼..但它的工作原理無論如何,感謝 – Blauhirn 2015-04-02 19:11:50

+0

不要忘記如果你覺得它對你有幫助 – CKing 2015-04-03 07:17:56