When do I have to change the serialVersionUID?

Viewed 24221

I know that I can use serialVersionUID to control the version of classes. And I read that I can then add or remove fields and the class will still be compatible, it will just use default values.

When must I change the serialVersionUID?

6 Answers

For the sake of completeness, here's a list of changes that break the compatibility of Java serialization according to the java 8 spec:

  • Deleting fields
  • Moving classes up or down the hierarchy
  • Changing a nonstatic field to static or a nontransient field to transient
  • Changing the declared type of a primitive field
  • Changing the writeObject or readObject method so that it no longer writes or reads the default field data or changing it so that it attempts to write it or read it when the previous version did not.
  • Changing a class from Serializable to Externalizable or vice versa
  • Changing a class from a non-enum type to an enum type or vice versa
  • Removing either Serializable or Externalizable
  • Adding the writeReplace or readResolve method to a class

To declare your own serialVersionUID in java, type this in the serialized object class:

@Serial

private static final long serialVersionUID = desired_number;

Related