This question has been the subject of some lively discussions in my team. My personal choice is to use
@SuppressWarnings("serial")
My thoughts are that it means there is one less thing to maintain compared to using
serialVersionUID
Am I correct in thinking that using this allows the compiler to generate the UID and is therefore more likely to pick up changes to the class?
My biggest fear is that relying on a developer to change the UID when they change the class is more likely to lead to unforeseen errors.
Are there any pitfalls to my approach? Has anyone else had good or bad experiences using either of these approaches?
The serialization at runtime associates with each serializable class a version number called a serialVersionUID, which is used during deserialization to verify that the sender and receiver of a serialized object have loaded classes for that object that are compatible with respect to serialization.
Simply put, we use the serialVersionUID attribute to remember versions of a Serializable class to verify that a loaded class and the serialized object are compatible. The serialVersionUID attributes of different classes are independent. Therefore, it is not necessary for different classes to have unique values.
Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent.
1L. Puts serialVersionUID=1L ; It should be sufficient in most cases.
It boils down to this questions:
"Different code" can mean several things:
In these cases you should strongly adhere to the Serialization contracts - and this not done by just setting serialVersionUId
- usually you must also overwrite the methods for serialization and deserialization to cope with different versions.
If - on the other hand - the same program reads and writes the stuff for something like an internal cache and that cache can be rebuild from scratch on when the software is updated - then feel free to make your life as easy as you can.
Between these extremes are of course various shades of grey.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With