Sal
Sal

Reputation: 3269

Multiple inherited serialization maintaining backward compatability

My org uses a custom serialization technique, where we store objects iteratively using an output stream. I'm running into the following issue:

Parent and Child classes implement Serializable. Parent class has fields a,b,c, and Child class has e. I added the field d to Parent and updated the parent's serialization, and now our old clients cannot read the Child serialization code properly. This is because the Child serialization code goes:

OutputStream in = getCurrentOutStream();

current_serialization_num = readVersionNum(in) // The version num is similar to Java's UID and is updated when fields are added.
readParent(in)
e = readField(in)

Since the serialization is done through a DataOutputStream, good XML reader can't take care of this. I have an ugly solution to this problem, but it won't extend well at all, so I'd rather not pollute the reader's mind by introducing it. However, I'd really like to hear how other's would handle a similar situation.

Upvotes: 1

Views: 146

Answers (2)

Mitch Connor
Mitch Connor

Reputation: 776

Ok see thats the issue. I understand you're using this class to serialize your data, however, this is a class def. issue not a serialization issue. You have constructed your class to read the file in in a specific way and now you are constructing the file differently. It won't "serialize" because it IS NOT the same type of file anymore. If you say: Im making a file with a then b then c fields and this class will read in the first field as a and the second as b etc. then change the file to be made with b,c, then a. The old class will still think 'a' is first and there is no reason it shouldn't.

Upvotes: 1

Hamed Moghaddam
Hamed Moghaddam

Reputation: 559

Objects created by old Parent got serialized by the old serialVersionUID. New objects get serialized by new serialVersionUID. The way you are implementing that, Child cannot read the old objects as well as the new one at the same time.

You either have to have a same serialVersionUID. If compiler complains put a suppress annotation. You want to clearly communicate compiler it is the same object.

Upvotes: 1

Related Questions