2015-06-20 18 views
12

近日在採訪中,我問了一個問題:如何在Java類序列只有極少數的性質

有一個Java類100點的屬性和我應該能夠僅僅的2連載屬性。這怎麼可能?

標記所有98個屬性並不是答案,因爲它效率不高。 我的答案是將這些屬性劃分爲一個單獨的類並使其可序列化。

但有人告訴我,我不會允許修改班級的結構。 那麼,我試圖在網上論壇找到答案,但徒勞無功。

+1

我只想指出序列化在我的Java生產體驗中並不是真正的東西。有很多更快,更好的方法可以產生與其他語言良好互操作的輸入,並且在Java中產生的尺寸更小。 (更不用說對象必須意識到其存儲表示的整體混合事物)。 –

回答

2

你可以重寫序列化行爲不使用Externalizable接口

你需要添加下面的方法和做要緊那裏,

private void writeObject(ObjectOutputStream out) throws IOException; 

private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException; 

例如類可能看起來像這樣,

class Foo{ 
    private int property1; 
    private int property2; 
    .... 
    private int property100; 

    private void writeObject(ObjectOutputStream out) throws IOException 
    { 
    out.writeInt(property67); 
    out.writeInt(property76); 
    } 

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException 
    { 
    property67 = in.readInt(); 
    property76 = in.readInt(); 
    } 
} 

有關更多詳細信息,請參閱this

12

如果是幾乎沒有的字段,那麼你總是可以將它們標記爲transient。但是如果你在搜索時需要更多的控制邏輯,那麼Externalizable就是答案。您可以通過執行Externalizable接口的方法writeExternalreadExternal方法來覆蓋序列化和deserilization過程。

這裏是小的代碼來向您展示如何序列只有幾個字段

public class Person implements Externalizable { 

    String name; 
    int age; 

    public Person() { } 

    Person(String name, int age) { 
    this.name = name; 
    this.age = age; 
    } 


    public void writeExternal(ObjectOutput out) throws IOException { 
    out.writeObject(name); 
    //out.writeInt(age); // don't write age 
    } 

    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { 
    name = (String) in.readObject(); // read only name and not age 
    } 
} 
+1

「但我被告知,我不會被授予該課程的實施。」 – EJP

8

答案是爪哇短暫關鍵字。 如果你創建了一個類的屬性,它將不會被序列化或反序列化。 例如:

private transient String nonSerializeName; 
相關問題