Tech

Guides
 

Choose your own version of serialisation in Java

By David Petersheim, Builder.com
Friday, September 23, 2005 01:35 PM
If you want to use serialisation but not break your classes, follow these simple instructions.
If you've ever used serialisation 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 serialisation by changing your classes.

When you serialise an object, class meta information is serialised along with the object's state. One of the pieces of metadata that is written is the class' serial version. When you attempt to recreate an object from serialised data, if the current class' version doesn't match the version number found in the serialised 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 serialised 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 deserialise 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 serialised, then these values will not be initialised when the data is deserialised and no errors will be thrown. If properties have been removed since the data was serialised, then the data for these properties will be ignored when the instance is reconstituted from serialised data.

In either case, no errors will be thrown, but you won't know that some properties haven't been initialised 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;



WORTHWHILE?

0

0 votes
Blog

Talkback 0 comments

There are currently no comments for this post.


Guest user

Guest user

Level: 
Joined: —
Already a member? Log in »



 

Loading...

Whitepapers/Case Studies

Downloads

Java News



Tech Jobs Now!