Home / Java Patterns and Pitfalls     frequal.com

Practical Guidelines for Java Serial Version ID and Serialization

Here are practical guidelines for using Java serialization and Serial Version IDs.
  • Add Serial Version IDs to Your Classes Immediately
  • How To Compute a Version ID

Add Serial Version IDs to Your Classes Immediately

You should add a Serial Version ID to your Serializable classes as soon as you create them. This guarantees that if you make changes to the class and save the class at different times that you won't end up with different serial version IDs in the saved files.

For example, if you save a object of Class C version 1 (C1) which doesn't have a version ID, then you modify it to version 2 (C2) and save it, you'll have two saved files, one with C1 and one with C2 objects. At this point no matter what serial version ID you put in the class, you will be unable to deserialize one of the saved files.

The caveat to versioning your Serializable classes is that you are then restricted to making so-called "compatible" changes -- adding fields or methods for example, but not removing fields or methods.

How To Compute a Version ID

The serialver tool comes with Sun's Java Development Kit (JDK). It take a full class name on the command line and returns the serial version ID for that compiled class, or can be run with the "-show" parameter to launch a small interactive GUI.

So if your class is com.frequal.Foo, run

serialver com.frequal.Foo
and you'll get output like this:
com.frequal.Foo:    static final long serialVersionUID = -6618469841127325812L;
Take the code starting with "static" and place it inside your class with other static variables. Now the serial version ID is locked in the class.

Read more practical Java tips here.

Last modified on 26 Jul 2008 by AO

Copyright © 2020 Andrew Oliver