[英]Java: how to serialize a 3rd party library produced Java Object?
所以我在項目中使用專有的java庫,我無法訪問源代碼。
它拋出一個Message對象,顯然我無法實現Serializable。 它是在整個運行時生成的。
我有什么選擇? 有沒有辦法將Message對象序列化為字節數組並返回到對象中?
更新:我能夠將對象序列化為JSON( http://code.google.com/p/json-io/ ),但無法將其轉換回對象,因為它返回null。 所以我試圖使用下面的代碼將其轉換為字節數組。 還是行不通。
public byte[] toByteArray (Object obj)
{
byte[] bytes = null;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
try {
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(obj);
oos.flush();
oos.close();
bos.close();
bytes = bos.toByteArray ();
}
catch (IOException ex) {
//TODO: Handle the exception
}
return bytes;
}
public Object toObject (byte[] bytes)
{
Object obj = null;
try {
ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
ObjectInputStream ois = new ObjectInputStream (bis);
obj = ois.readObject();
}
catch (IOException ex) {
//TODO: Handle the exception
}
catch (ClassNotFoundException ex) {
//TODO: Handle the exception
}
return obj;
}
您可以編寫一個可序列化的包裝器,並存儲重新創建Message對象所需的所有內容。
XStream是一種方法。
如果對象是Java bean,則可以使用java.beans.XMLEncoder
和java.beans.XMLDecoder
進行序列化。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.