2010-05-06 74 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给你更多的控制权,但。

相关问题