History of the Issue
Since the inception of Java, there has been a need to persist objects between application sessions — to transmit them over the network, store them in a database, or on disk. To address this, the Serializable interface was introduced, allowing objects to be transformed into a stream of bytes and vice versa (serialization and deserialization).
Problem
If a class does not implement the Serializable interface, an attempt to serialize its instance will throw an exception. Moreover, serialization preserves not only the values of fields but also their state, so an incorrect implementation can lead to unexpected vulnerabilities, object recovery errors, or even data loss.
Solution
The Serializable interface is a marker interface, which means it does not contain any methods. For correct serialization, it is advisable to explicitly declare serialVersionUID, as well as use the transient keyword for fields that should not be serialized.
Example code:
import java.io.Serializable; public class User implements Serializable { private static final long serialVersionUID = 1L; private String username; private transient String password; // will not be serialized public User(String username, String password) { this.username = username; this.password = password; } }
Key features:
Is it mandatory to explicitly declare the serialVersionUID field?
No, it is not mandatory, but if it is not declared, it will be generated automatically. However, when changes are made to the class, recovering an old serialized version may lead to an InvalidClassException. Therefore, it is better to always explicitly declare this field.
Are static fields serialized?
No, only non-static (instance) fields are serialized. Static fields belong to the class, not to the object, and therefore their values are not saved and restored during serialization and deserialization.
Can an object with fields that do not implement Serializable be serialized?
No, if at least one non-static field is not serializable and not declared as transient, an attempt to serialize will throw a NotSerializableException.
In a user caching application, serialVersionUID was not specified, and during code updates, the structure of the User class was changed. Upon application startup, an InvalidClassException occurred and all serialized data was lost.
Pros:
Cons:
In a similar project, serialVersionUID was always explicitly specified, and all fields not subject to serialization were made transient. As a result, serialized objects were successfully loaded after minor class structure changes.
Pros:
Cons: