The Blob object does not work properly even if the class is serialized


I have class which is seralized and does convert a very large amount of data object to blob to save it to database.In the same class there is decode method to convert blob to the actual object.Following is the code for encode and decode of the object.

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

    catch (Exception e)
        _log.error("Exception caught while encoding/zipping Scheduled STDReport", e);
    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;
        ObjectInputStream ois = new ObjectInputStream(bais);

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

The problem here is whenver I change something else in this class means any other method,a new class version is created and so the new version the class is unable to decode the originally encoded blob object. The object which I am passing for encode is also seralized object but this problem exists. Any ideas thanks

Yup, Java binary serialization is pretty brittle :(

You can add a static serialVersionUID field to the class so that you can control the version numbers... this should prevent problems due to adding methods. You'll still run into potential issues when fields are added though. See the JavaDocs for Serializable for some more details.

You might want to consider using another serialization format such as Protocol Buffers to give you more control though.