how-to

Classes

How to use "serialVersionUID" with serialization

When you serialize class instance, deserialization is possible only when the class is same -> when you serialize class and make some changes in the class code, deserialization is then a problem. The reason is that the class has other computed hash value - and this hash value work as class identifier.

More about class hash value you can find here.

BUT...

You can set your own hash value for your class. This solving enable serialize the class, make some changes, and deserialize class again.

For example, you have class:

import java.io.Serializable;

public class Person implements Serializable {
          
  public Person() {}
      
  String name;
  int age;  
}

Then you call serialization, like here..

Then you make some changes in the class, for example you add one field:

import java.io.Serializable;

public class Person implements Serializable {

  public Person() {}

  String name;
  int age;
  int age1;
}

In this case is a deserialization problem.

SOLVING...

Add to class field serialVersionUID. That field is now new class ID for serialization.

import java.io.Serializable;

public class Person implements Serializable {

  public Person() {}

  String name;
  int age;

  private static final long serialVersionUID = 100L;
}

After changes in the class is in this case deserialization working.