2012-01-20 40 views
0

我正在使用XMLEncoder將對象圖寫入XML文件。 這工作正常,除了UUID屬性(其名稱ID在我的JavaBean) 我知道我需要一個PersistenceDelegate來完成它。我寫了下面一個:使用XMLEncoder序列化UUID

class UuidPersistenceDelegate extends PersistenceDelegate { 
    protected Expression instantiate(Object oldInstance, Encoder out) { 
     UUID id = (UUID) oldInstance; 
     return new Expression(oldInstance, id.getClass(), "fromString", new Object[]{ "id" }); 
    } 
} 

並將其設置爲編碼器:

encoder.setPersistenceDelegate(UUID.class, new UuidPersistenceDelegate()); 

在運行時調用encoder.writeObject時,我得到以下異常(...):

java.lang.IllegalArgumentException:無效的UUID字符串:ID

有誰知道如何讓這個工作?

回答

0

歡迎來到SO。你非常接近你的解決方案,你的代碼有一個小問題。你傳入的字符串「id」到你的參數參數中,我敢肯定你不想這樣做。試試這個:

protected Expression instantiate(Object oldInstance, Encoder out) { 
    UUID id = (UUID) oldInstance; 
    return new Expression(oldInstance, UUID.class, "fromString", new Object[]{ id.toString() }); 
} 

輸出的XML並不漂亮,但至少你會擺脫你的錯誤。

1

我還沒有看到任何人真正正確回答這個問題和實際工作:

public class UUIDPersistenceDelegate extends PersistenceDelegate { 
private HashSet<UUID> hashesWritten = new HashSet<UUID>(); 

public Expression instantiate(Object oldInstance, Encoder out) { 
    UUID id = (UUID) oldInstance; 
    hashesWritten.add(id); 
    return new Expression(oldInstance, UUID.class, "fromString", new Object[]{ id.toString() }); 
} 

protected boolean mutatesTo(Object oldInstance, Object newInstance) { 
    return hashesWritten.contains(oldInstance); 
} 

}