Home > Back-end >  Can Java Serialization UID numbering start at 1
Can Java Serialization UID numbering start at 1

Time:07-12

The vast majority of examples of a Java serialVersionUID I have seen has a very long long value - see for example here where the given example is static final long serialVersionUID = 10275539472837495L or even the documentation which gives an example of static final long serialVersionUID = 42L

Is there any reason, though, that I can't call the first version of my class(es) static final long serialVersionUID = 1L the second 2L and so on? It compliles, serialises and deserialises fine but I was wondering if there were deeper reasons that made it not best practice.

CodePudding user response:

From the Serializable Interface Docs:

If a serializable class does not explicitly declare a serialVersionUID, then the serialization runtime will calculate a default serialVersionUID value for that class based on various aspects of the class, as described in the Java(TM) Object Serialization Specification. However, it is strongly recommended that all serializable classes explicitly declare serialVersionUID values, since the default serialVersionUID computation is highly sensitive to class details that may vary depending on compiler implementations, and can thus result in unexpected InvalidClassExceptions during deserialization.

When you see a serialVersionUID such as 10275539472837495L, it is most probable one that was generated by the serialization runtime.

So, why would you explicitly set the serialVersionUID to one generated by the runtime? Suppose you forgot to set the serialVersionUID to a specific value such as 1L, and you serialized a class. After a while, you make some changes to the class implementing the Serializable interface and all out of sudden, an InvalidClassException is thrown because the generated serialVersionUIDs do not match anymore. To fix this, you can explicitly set the serialVersionUID to that generated with the previous version. This is pretty much how one might end up with these long serialVersionUIDs.

To avoid this alltogether, it is recommended to explicitly declare serialVersionUID values, as stated in the docs.

  • Related