Implementing Java Serializable is not as simple as it seems

Sometimes we have to send objects “over the wire” to remote machines. Or we have to write them on disk. Or for any other unknown reason, you have to make your entity class Serializable. Maybe you are using an API that asks for it and you don’t know, nor care, why.

So it is simple, right? Just add implements Serializable to your class and you are done. Well… not really. The problem is that a lot of developers think this way, just because of a lack of knowing better. So this post is here to save you!

Lets start understanding what implementing Serializable means. When you write something like

public class MyClass implements Serializable {
    private String myString;

you are basically saying that your entity has one field, myString, which is part of the logical representation of the class. So the compiler will assume it can use this information to, say, serialize (write) the object to disk, and do the opposite when deserializing it.

So far so good. Now suppose you sent this class to a friend. After a while, you evolve your class and add an utility method, but your friend still uses the old version. Well, now the serialized forms of your local class and your friends’ are incompatible. If you try to deserialize a class your friend serialized, you will get an InvalidClassException.

Fortunately, the solution to this problem is easy: declare a serialVersionUID, like this:

public class MyClass implements Serializable {
    private static final long serialVersionUID = 42L;
    private String myString;

If you do this from the start, both your object and your friends’ will be compatible! Some IDEs even do this automatically for you =)

Now, you may wonder why that happened, if all you did was to add an utility method, something in principle unrelated to the logical representation of the class? What happens is that the default algorithm for generating a serialVersionUID takes all kinds of class members into account, which includes our utility friend.

This is all for now. But there is more to this topic. Next, we will look into more complex problems related to object serialization. Get ready!

This entry was posted in java and tagged , , , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s