Eclipse issues warnings when a serialVersionUID
is missing.
The serializable class Foo does not declare a static final serialVersionUID field of type long
What is serialVersionUID
and why is it important? Please show an example where missing serialVersionUID
will cause a problem.
It would be nice if CheckStyle could verify that the serialVersionUID on a class that implements Serializable has a good value, i.e. that it matches what the serial version id generator would produce. If you have a project with lots of serializable DTOs, for example, remembering to delete the existing serialVersionUID and regenerate it is a pain, and currently the only way (that I know of) to verify this is to regenerate for each class and compare to the old one. This is very very painful.
I can't pass up this opportunity to plug Josh Bloch's book Effective Java (2nd Edition). Chapter 11 is an indispensible resource on Java serialization.
Per Josh, the automatically-generated UID is generated based on a class name, implemented interfaces, and all public and protected members. Changing any of these in any way will change the
serialVersionUID
. So you don't need to mess with them only if you are certain that no more than one version of the class will ever be serialized (either across processes or retrieved from storage at a later time).If you ignore them for now, and find later that you need to change the class in some way but maintain compatibility w/ old version of the class, you can use the JDK tool serialver to generate the
serialVersionUID
on the old class, and explicitly set that on the new class. (Depending on your changes you may need to also implement custom serialization by addingwriteObject
andreadObject
methods - seeSerializable
javadoc or aforementioned chapter 11.)I generally use
serialVersionUID
in one context: When I know it will be leaving the context of the Java VM.I would know this when I to use
ObjectInputStream
andObjectOutputStream
for my application or if I know a library/framework I use will use it. The serialVersionID ensures different Java VMs of varying versions or vendors will inter-operate correctly or if it is stored and retrieved outside the VM for exampleHttpSession
the session data can remain even during a restart and upgrade of the application server.For all other cases, I use
since most of the time the default
serialVersionUID
is sufficient. This includesException
,HttpServlet
.