Add a serialVersionUID to a serializable class that is already in use
I've got a Serializable
class that has been in use in production since about 2004. However, the guy who wrote it forgot to generate a serialVersionUID
.
The whole thing sort of works (there is a big comment warning to not touch anything in the class), but while working in a related different class I've had a InvalidCastException
, so I want to add serialVersionUID
to be sure that the class works properly.
The question is, is it possible to add such a field, without existing serialized instances breaking? There are a lot of them, and there is no easy way to modify them.
My idea came from seeing the exception message, which is something along the lines of:
java.io.InvalidClassException: the.problematic.Class; local class inco开发者_JS百科mpatible: stream classdesc serialVersionUID = -8802277085918151566, local class serialVersionUID = -3137213695071887162"
I've thought that I could use the implicit serial (stream classdesc in the trace) as the serial, and it should retain backwards compatibility. Is this correct? I'm (more or less) sure that all the serialized instances that we've got across the system are of the same version.
Yes, specifying the exact same value for serialVersionUID
as the computed on is should prevent backwards compatibility (Eclipse for example has an option to do that, called "Add generated serial version ID").
You have to be carefull, if you check the serialVersionUID which you read from a serialized stream (simple: just change the object and read it in, the exception will tell you the expected value) you can put that into your code and it will work with this specific environment. However another JDK (for example IBM vs. SUN) on antother platform might have incompatible different serialVersionUIDs. (worst case is you need to compute the serialversionuid from a list of known values for your supported VMs).
精彩评论