2010-05-06 73 views
0

我有seralized的類,它將大量的數據對象轉換爲blob以將其保存到數據庫。在同一個類中有解碼方法將blob轉換爲下面是對象的編碼和解碼代碼。儘管類是seralized,Blob對象仍然無法正常工作

private byte[] encode(ScheduledReport schedSTDReport) 
{ 
    byte[] bytes = null; 
    try 
    { 
     ByteArrayOutputStream bos = new ByteArrayOutputStream(); 
     ObjectOutputStream oos = new ObjectOutputStream(bos); 
     oos.writeObject(schedSTDReport); 
     oos.flush(); 
     oos.close(); 
     bos.close(); 
     //byte [] data = bos.toByteArray(); 
     //ByteArrayOutputStream baos = new ByteArrayOutputStream(); 
     //GZIPOutputStream out = new GZIPOutputStream(baos); 
     //XMLEncoder encoder = new XMLEncoder(out); 
     //encoder.writeObject(schedSTDReport); 
     //encoder.close(); 
     bytes = bos.toByteArray(); 
     //GZIPOutputStream out = new GZIPOutputStream(bos); 
     //out.write(bytes); 
     //bytes = bos.toByteArray(); 

    } 
    catch (Exception e) 
    { 
     _log.error("Exception caught while encoding/zipping Scheduled STDReport", e); 
    } 
    decode(bytes); 
    return bytes; 
} 


/* 
* Decode the report definition blob back to the 
* ScheduledReport object. 
*/ 
private ScheduledReport decode(byte[] bytes) 
{ 
    ByteArrayInputStream bais = new ByteArrayInputStream(bytes); 
    ScheduledReport sSTDR = null; 
    try 
    { 
     ObjectInputStream ois = new ObjectInputStream(bais); 

     //GZIPInputStream in = new GZIPInputStream(bais); 
     //XMLDecoder decoder = new XMLDecoder(in); 
     sSTDR = (ScheduledReport)ois.readObject();//decoder.readObject(); 
     //decoder.close(); 
    } 
    catch (Exception e) 
    { 
     _log.error("IOException caught while decoding/unzipping Scheduled STDReport", e); 
    } 
    return sSTDR; 
} 

這裏的問題是whenver我改變別的東西在這個類 意味着任何其他方法,創建一個新的類版本,因此新版本的類是無法解碼的原始編碼的blob對象。我傳遞給對象的對象也是seralized對象,但存在這個問題。任何想法感謝

回答

2

是啊,Java的二進制序列化是非常脆:(

您可以將靜態serialVersionUID字段添加到類,這樣就可以控制版本號......這應該防止因添加方法的問題你還是會碰到時字段添加,雖然潛在的問題。參考JavaDoc Serializable的一些細節。

你可能要考慮使用其他的序列化格式such as Protocol Buffers給你更多的控制權,但。

相關問題