代码之家  ›  专栏  ›  技术社区  ›  GustyWind

即使类已序列化,blob对象也无法正常工作

  •  0
  • GustyWind  · 技术社区  · 15 年前

    我有一个类,它是序列化的,它将大量的数据对象转换成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对象。我要传递给encode的对象也是seralized对象,但这个问题存在。有什么想法吗谢谢

    2 回复  |  直到 15 年前
        1
  •  2
  •   Jon Skeet    15 年前

    YUP,Java二进制序列化是相当脆弱的:

    可以添加静态 serialVersionUID 字段,以便您可以控制版本号…这样可以防止由于添加方法而出现问题。但是,添加字段时仍会遇到潜在的问题。参见javadocs Serializable 更多细节。

    您可能需要考虑使用其他序列化格式 such as Protocol Buffers 给你更多的控制权。

        2
  •  0
  •   Bozho    15 年前

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