Serialization and Deserialization In Java — What is SerialVersionUID and When to Regenerate It
Serialization and Deserialization In Java, SerialVersionUID Generation and How to Auto Add It in IntelliJ IDEA
Serialization and Deserialization In Java
Serialization is a mechanism of converting the state of an object into a byte stream.
Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory.
This mechanism is used to help an object travel across a network and persist it.
To make a Java object serializable we implement the “java.io.Serializable” interface.
- Only non-static data members are saved via serialization.
- Static data members and transient data members are not saved (Make a non-static data member “transient” if you don’t want to save it).
The sequence of items in the stream:
- Class Name
- Class Modifiers (as 32 bit integer)
- Name of each interface (sorted by name)
- Each field (except private static/private transient, sorted by field name, as 32 bit integer)
- Class Initializer
- Each non-private constructor (sorted by name/signature)
- Each non-private method (sorted by name/signature)
- SHA-1 Algorithm
- Hash value from 1st and 2nd 32-bit values of SHA-1
SerialVersionUID
A Serializable class can declare its own UID — serialVersionUID explicitly by declaring a field name that is static, final and of type long.
It is calculated based on the structure of your class — fields, methods, etc.
You should explicitly declare a serialVersionUID in your serializable class.
If not, JVM will generate one automatically.
serialVersionUID must be kept the same value for serialization and deserialization or an “InvalidClassException” will be thrown.
When to Regenerate?
This is stated detailed in “Java Object Serialization Specification”.
Incompatible Changes:
- Deleting fields
- Moving classes up/down in the hierarchy
- Changing non-static field -> static or non-transient -> transient
- Changing the declared type of primitive field
- Changing writeObject/readObject method
- Changing a class from Serializable -> Externalizable or Externalizable -> Serializable
- Changing a class from non-Enum type -> Enum or Enum -> non-Enum type
- Removing Serializable/Externalizable
- Adding writeReplace/readResolve
Compatible Changes
- Adding fields
- Adding/Removing classes
- Adding/Removing writeObject/readObject methods
- Adding java.io.Serializable
- Changing the access to a field
- Changing a field from static -> non-static or transient -> non-transient
How to generate serialVersionUID in IntelliJ IDEA
In IntelliJ IDEA -> Preferences, search for “Serializable class without ‘serialVersionUID’”.
Find “Serializable class without ‘serialVersionUID’”. Check it and select “Severity” level of your choice.
If you select “Error”, your class will give you an error same as below:
When you click on “Add ‘serialVersionUID’ field”, it will generate one for you:
Happy Coding!