If you are working with eclipse and implementing the serializable interface to your own class, most likely that you would get the following error if you have not declared the serialVersionUID. The error is:
The serializable class XXXX does not declare a static final serialVersionUID field of type long
What is serialVersionUID?
Having looked at basics of serialization, we will look at the concept of serialVersionUID. By default, every time an object is serialized; Java automatically associates it an auto-calculated version ID based on the object structure. And during deserialization, Java checks for the same version ID and if it doesn’t match throws an Exception. Why does Java perform this check? Consider a scenario, where we have serialized the object but later removed the transient keyword from one of the instance variable and so the version ID changes. But assume we didn’t serialize the object after this change and then deserialize it. How does the deserializing class know about this change?
One way, Java resolves this discrepancy is by checking if the version ID matches between deserialized and serialized class. So this serialVersionUID acts like a version control for the Serializable class by checking the deserialized object compatibility with the current definition of same class.
Why worry about this if Java takes care of this ? If we are using Eclipse IDE and after we implement java.util.Serializable, we will notice a warning “didn’t declare a static final serialVersionUID of type long”. If we use Eclipse IDE, clicking on that warning will generate a serialVersionUID. And there are two options: use a “default” or “generated version id”. According to Java experts, we should avoid using this default version ID. Hence we should always use the other option “generated version id”.
Eclipse Configuration For serialVersionUID Warning
If you feel that there is no need for this warning to be shown while you are coding, this can be suppressed permanently by changing the default configurations in eclipse. This settings can be configured at the project level or the work space level. You can follow the steps and change the settings.
- Right click on the Project and click on the properties menu.
- A dialog window appears with the options to change the settings. Select “Java Compiler” and the select “Error / Earnings”.
- Change the value of the field Potential programming problems section, change Serializable class without serialVersionUID: to Ignore
The same thing can be found in this screenshot.