X
Business

Choosing your own version of serialization

If you've ever used serialization in Java, the first thing you probably noticed is how easy it is to code. The second thing you probably noticed is how easy it is to break serialization by changing your classes.
Written by David Petersheim, Contributor
If you've ever used serialization in Java, the first thing you probably noticed is how easy it is to code. The second thing you probably noticed is how easy it is to break serialization by changing your classes.

When you serialize an object, class meta information is serialized along with the object's state. One of the pieces of metadata that is written is the class's serial version. When you attempt to recreate an object from serialized data, if the current class's version doesn't match the version number found in the serialized data, then an InvalidClassException will be thrown.

You can prevent this error by handling the versioning of your classes yourself. To provide a version number for your class, define a static final long class member with the name serialVersionUID. When you compile your class, this member's value will be used as the version for your class.

If you're trying to use serialized data from a class that you didn't version, then you can use the serialver command line tool to extract the version number from the old class. If you then compile the new class with this version number, you'll be able to deserialize the old data using the new class.

There are precautions to take when you assume the responsibility of versioning your classes. If the class has added new attributes since the former version was serialized, then these values will not be initialized when the data is deserialized and no errors will be thrown. If properties have been removed since the data was serialized, then the data for these properties will be ignored when the instance is reconstituted from serialized data.

In either case, no errors will be thrown, but you won't know that some properties haven't been initialized or that data has been abandoned. As you can see, providing your own versioning for your Java classes is simple and convenient but also has risks.

Here is a sample class with programmer-provided versioning and the output from the serialver tool:

// code
import java.io.Serializable;
public class Zed implements Serializable {
    private double value;
    private static final long serialVersionUID = 4;
    public double getValue() {
        return this.value;
    }
    public void setValue(double value) {
        this.value = value;
    }
}
command and output
>serialver Zed
Zed:  static final long serialVersionUID = 4L;

David Petersheim is the Director of Application Development with Genscape, Inc. He designs and develops server-side applications to acquire and process real-time energy data.

Editorial standards