Just wondering why some of the creators of Java put this seemingly
useless long type number in their source code.
here is more than you wanted to know about serialVersionUID . Your
answer is buried in there, as well as some other question you have
asked or are about to ask.
It is probably best to assign your own serialVersionUID for each
class:
static final long serialVersionUID = 3L;
This must change if any characteristics of the pickled Object change.
If you don't handle it manually, Java will assign one based on hashing
the code in the class. It will thus change every time you make a very
minor code change that may not actually affect the pickled Objects.
This will make it more difficult to restore old Object streams.
Note it is spelled serialVersionUID not SERIALVERSIONUID as is
traditional for static final constants.
You sometimes see bizarre, what appear to be random, numbers chosen
for the serialVersionUID. This is just a programmer freezing an
automatically generated serialVersionUID, because he forgot to assign
a sensible version 1 number to get started.
Not only should the base serialisable class get a serialVersionUID,
but also could each subclass get its own. That way you can
individually track which Objects are no longer consistent with the
class definition. The serialVersionUID does not have to be globally
unique. Think of it as a version number for tracking changes to the
code in a particular class independently of changes in its base class.
I just increment the serialVersionUID by one each time I modify a
class in a way that would change its serialisation characteristics
e.g.
Add a field.
Rename a field.
Change the type of a field.
Change the name of the package or class.
Delete a field
I don't increment when I:
reorder the fields.
add a method.
change the signature of a method.
rename a method.
Change or add a static field.
I am not sure it if is necessary to increment the serialVersionUID of
every subclass when a field in a class changes. If you find out,
please let me know.
You can think of serialVersionUID as a primitive mechanism to record
which version of a class was used to create any particular historical
serialised file. Unfortunately, there is no tool to summarise a
mysterious serial file, telling you which classes it uses and which
versions of them. Hint, hint… If you try to read the file and you
guess incorrectly, it just blows up.
To partly get around this problem, at the head of the serialized file,
as a separate Long, I write out the serialVersionUID of the key class
of the file. There, it is easily accessible as an identifier to how
old the serialised file is. It is automatically up to date. You can
also write a similar file type identifier Long as the very first
field.