2016-10-25 50 views
1

我有序列化爲一個文件對象的列表:Java的反序列化如何忽略屬性

class MyClass implements Serializable { 

    public String location; 
    public SomeClass lastUpdatedAt; 

} 

不幸的是,我現在有這個類的一個新版本,我們沒有SomeClass的了;原因是複雜的,但我需要序列化這回這個新的形式(這是一個例子類,而不是實際的類明顯):

class MyClass implements Serializable { 

    public String location; 

} 

總之,我想忽略在反序列化的屬性。

請不要改變原來的類源文件。我只有在新的源文件

然而ObjectInputStream的當它試圖找到SomeClass的在classpath失敗:

try { 
    FileInputStream fis; 
    ObjectInputStream is; 
    File f = getSavedFile(); 
    if (f.exists()) { 
     fis = new FileInputStream(f); 
     is = new ObjectInputStream(fis); 
     ArrayList<MyClass> result = (ArrayList<MyClass>) is.readObject(); //fails 
     is.close(); 
     fis.close(); 
     } 
    } 
    catch (Exception e) { 
     //ClassNotFound exception because SomeClass is not on the classpath. 
     e.printStackTrace(); 

    } 

我知道你可以擴展ObjectInputStream的和實施的東西在那裏,但是我對序列化並不熟悉,希望有人解決同樣的問題。

回答

1

使其瞬間將系列化

public transient SomeClass lastUpdatedAt; 

根據jls-8.3.1.3

Variables may be marked transient to indicate that they are not part of the persistent state of an object.

+0

與上述相同的問題。我無法對原始來源進行任何更改。它是一個正在運行的服務,我需要更新一個全新的,同時也保留遺留數據序列化到文件....總之 – breakline

1
class MyClass implements Serializable { 

    public String location; 
    public transient SomeClass lastUpdatedAt; 

} 

也許你有與成功排除。如果不起作用,那麼你必須重寫該方法。

因爲這個原因,我不喜歡自動化的序列化,我手動:實現什麼字段序列化和如何。

每次更新代碼時,如果使用build in函數,將會遇到與向後兼容性相同的問題。

+0

This'd工作,但重要的東西(我會編輯我的問題)我忘了:我不能改變原始類的來源。 – breakline

0
ArrayList<MyClass> result = (ArrayList<MyClass>) is.readObject(); //fails 

其實這會失敗,因爲元素列表簽名不匹配!由於MyClass有一個或多個字段被重命名,添加,刪除,鍵入已更改。

MyClass { int a; } 

MyClass { String a; } 

將打破反序列化。

你可以嘗試重寫equals()hashCode()方法,以使MyClassNew看起來像MyClass。

Here你可以看到更多如何覆蓋現在所需的方法。這應該給你一個解決方案。

private void readObject(java.io.ObjectInputStream stream) 
      throws IOException, ClassNotFoundException { 
     location = (String) stream.readObject(); 
    } 
+0

這給了我一個錯誤:java.io.StreamCorruptedException:錯誤的格式:0 – breakline

+1

另外,我在兩個類中都有相同的serialVersionUID,至少 – breakline

+0

@breakline也是需要的,忘記提及,但它通常生成的Eclipse – matheszabi

相關問題