Reputation: 1665
There is a java class in our code which implements Serializable.It already has a serialVersionUUId defined in the class. Apart from that we also have another
static final String sVersion which is an integer.This class implements the readObject and writeObject api . In the readObject API it populates all the member variables using the InputStream and in the writeObject API , it gets an OutputStream and calls the writeObject method .
Now i need to add an array of booleans as a property for this class. Should i change the serialVersionUUID? What is the effect that would happen if i change/not change the version id? what is the best practice?Im trying to get into Effective java by joshua bloch , but need a quick easy to digest answer for this.
Thanks
Upvotes: 4
Views: 247
Reputation: 310840
This class implements the readObject and writeObject api. In the readObject API it populates all the member variables using the InputStream and in the writeObject API , it gets an OutputStream and calls the writeObject method.
Why? That's the default action if you don't provide those methods at all. [Although I don't know what exactly you mean by 'gets an OutputStream`, unless you mean the one provided as a parameter.]
However now that you're here, all you have to do in readObject()
is attempt to read the new fields and catch the exception that's thrown if they aren't there (OptionalDataException
?), and in writeObject()
write out the extra field.
Don't change the serialVersionUID
. You should instead explore the extensive object versioning support of Serialization, (a) to ensure that the class really is now serialization-incompatible, which per the specification is quite difficult to achieve; (b) to try a scheme such as custom read/writeObject() methods, readResolve/writeReplace() methods, serializableFields declarations, etc, to make sure that the stream remains compatible. Changing the actual serialVersionUID is a last resort, a counsel of despair.
Before proceeding any further you need to have a really good look at the Object Versioning section of the Object Serialization Specification. Serialization has a lot more support for class evolution than most people appear to be aware of, including other respondents to this question and the questions that they have linked to.
Upvotes: 2
Reputation: 6247
If there is a possibility that you might end up trying to deserialize an incompatible instance of the class, then yes, you should definitely update the serialVersionUID. If, on the other hand, your program always serializes and deserializes the data without saving it to persistent storage or the contract between your class and its callers can still be guaranteed, then you don't need to change the serialVersionUID.
See https://stackoverflow.com/a/286254/44737 and https://stackoverflow.com/a/285827/44737 for more information.
Upvotes: 0