I have an object from old Java code, and I now changed the serialized object code. I want to be able to read both the old files and the new files. I need a branching statement in readObject to do something like:
if (next object is int -- just poking, it might be an Object)
{
// we know we are in version 1
} else {
// read new version of object
}
is that possible to do?
Ok so basically the question is “How can we check with an
ObjectInputStreamwhether the next field is a primitive or an object?” and the answer as far as I can see is: You can’t.Which means the best solution I can see to keep backwards compatibility is to never remove primitives from the original version – keeping useless information blows up the size a bit, but otherwise that’s easy.
To add new fields, I can see two ways:
Keep the earlier message format identical and only add new objects at the end – you can then easily distinguish different versions by the message size (or more exactly you’ll get an IOException when reading data of v2 when you get a v1 object). That’s much simpler and generally preferred.
You can change objects from v1 to v2 and then do a simple
instanceofcheck. If you want to add primitives is to store their wrapper versions (i.e.Integeret al). Can save you some bytes, but Java’s serialization protocol was never efficient to begin with, so really that’s unnecessary complicated.