If I do not declare this constant ( serialVersionUID
) in a class that implements the Serializable
interface, I get a warning . But what does this constant serve, anyway? Does its value interfere with object serialization?
If I do not declare this constant ( serialVersionUID
) in a class that implements the Serializable
interface, I get a warning . But what does this constant serve, anyway? Does its value interfere with object serialization?
serialVersionUID
is for tracking the compatibility of serialized versions of classes.
This is because if you serialize an instance of a X
class and save it to a file, and some time later change the X
class and deserialize that instance, the deserialized data may not be compatible with the new version of the class once it has undergone a change.
And how do you define which version of the class is? With serialVersionUID
. That's what it's for.
The idea is that if you are going to create a A
serializable class, you declare something like private static final long serialVersionUID = 1L;
in it to define that this is the first version of the class. Then, if you make any structural changes incompatible with previous versions, you will change the serialVersionUID
to 2L
. In another change, it will change to 3L
, and so on. Obviously, if the change is small and no incompatibility is introduced, you should not change serialVersionUID
.
If you make an incompatible structural change in the class and do not change the serialVersionUID
, the deserialization of an incompatible instance will fail.
If you want to be able to read a different version of the class to be deserialized, you can implement the readObject()
and there, read% required%. The serialVersionUID
method can also be useful.
Finally, if you do not set any readObjectNoData()
, then one will automatically be generated for you from a hash taking into account the class name, superclasses, implemented interfaces, and class members (fields, methods, and builders). This means that it is very easy to happen from automatically generated% change% even if there are no significant changes in the class. For this reason, it is recommended that you always explicitly set serialVersionUID
.
Additional links for more information:
Java Object Serialization Specification - from Oracle.
Understanding the serialVersionUID - by Caelum.