【问题标题】:Blob object not working properly even though the class is seralized即使类已序列化,Blob 对象也无法正常工作
【发布时间】:2010-05-06 09:01:51
【问题描述】:

我有一个类,它是序列化的,并且确实将大量数据对象转换为 blob 以将其保存到数据库。在同一类中,有 decode 方法将 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;
}

这里的问题是每当我在这个类中更改其他内容时 表示任何其他方法,创建一个新的类版本,因此该类的新版本无法解码最初编码的 blob 对象。我为编码传递的对象也是序列化对象,但存在此问题。任何想法谢谢

【问题讨论】:

    标签: java serialization object blob


    【解决方案1】:

    是的,Java 二进制序列化非常脆弱:(

    您可以在类中添加静态serialVersionUID 字段,以便您可以控制版本号...这应该可以防止由于添加方法而出现问题。但是,添加字段时,您仍然会遇到潜在问题。有关更多详细信息,请参阅Serializable 的 JavaDocs。

    您可能需要考虑使用另一种序列化格式 such as Protocol Buffers 以提供更多控制权。

    【讨论】:

      【解决方案2】:

      您可以实现java.io.Externalizable,以便能够控制反序列化中序列化和预期的内容。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-03-15
        • 2021-06-30
        • 1970-01-01
        • 1970-01-01
        • 2012-06-04
        • 2020-07-19
        • 1970-01-01
        相关资源
        最近更新 更多