views:

89

answers:

2

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;
    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;
}

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

+2  A: 

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.

Jon Skeet
A: 

You can implement java.io.Externalizable so that you are able to control what is serialized and expected in deserialization.

Bozho