serialVersionUID and class changes
40 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)The serialVersionUID is a version number for a serializable class. Java writes it into the saved bytes, and on reading it checks that the class in the program has the same number. If the numbers differ, reading stops.
InvalidClassException after a change
serialVersionUID is a number stored with serialized data and kept in the class. When reading, Java compares the two, and if they differ it throws InvalidClassException.
InvalidClassException is thrown by readObject when the saved bytes do not fit the class in the running program. The most common cause: you saved objects, then edited the class, and now the old file will not load.
Example 1 · Adding one field breaks old data
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InvalidClassException;import java.io.ObjectInputStream;import java.io.Serializable;import java.util.Base64;
// Version 2 of the class: the email field was added after the data was savedclass Student implements Serializable { String name; int roll; String email;
Student(String name, int roll) { this.name = name; this.roll = roll; }}
public class ClassChangedDemo { // The bytes of student.ser, saved earlier by version 1 (only name and roll), // written as Base64 text so the whole demo fits in one file static final String SAVED_BY_V1 = "rO0ABXNyAAdTdHVkZW50pfJ3KYrK154CAAJJAARyb2xsTAAEbmFtZXQAEkxqYXZhL2xhbmcvU3RyaW5nO3hwAAAADHQABVByaXlh";
public static void main(String[] args) throws IOException, ClassNotFoundException { byte[] bytes = Base64.getDecoder().decode(SAVED_BY_V1); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { Student s = (Student) in.readObject(); System.out.println("Loaded " + s.name); } catch (InvalidClassException e) { System.out.println("Cannot load: " + e.getMessage()); } }}Cannot load: Student; local class incompatible: stream classdesc serialVersionUID = -6488993092781549666, local class serialVersionUID = -6109570741994644948
What this code does
SAVED_BY_V1holds the bytes of aStudentsaved before theemailfield existed. Neither version declaresserialVersionUID.- Adding
emailchanged the computed number, so the stored value and the local value differ andreadObjectthrowsInvalidClassException. - The second number is computed by your compiler and JDK, so it may differ on your computer. The exception is the same.
It happens even for a tiny edit, such as adding one field, when the class has no serialVersionUID of its own. The message shows the class name and two numbers: the version stored in the file ("stream classdesc") and the version of the class now ("local class"). The examples below need bytes saved by an older version of a class. Each one keeps those bytes as a short Base64 string, which is just a way to write bytes as plain letters, and turns them back into bytes with Base64.getDecoder().decode(...).
The generated versus declared value
If a class does not declare serialVersionUID, Java computes one from the class's details: its name, its fields, its constructors and methods, and their modifiers. Almost any edit gives a new number, so old data no longer matches.
Example 2 · See the computed and the declared value
import java.io.ObjectStreamClass;import java.io.Serializable;
class Fee implements Serializable { // no serialVersionUID: Java computes one String student; int amount;}
class Hostel implements Serializable { // declared by the programmer private static final long serialVersionUID = 1L; String block; int rooms;}
public class ShowVersionDemo { public static void main(String[] args) { long fee = ObjectStreamClass.lookup(Fee.class).getSerialVersionUID(); long hostel = ObjectStreamClass.lookup(Hostel.class).getSerialVersionUID(); System.out.println("Fee (computed): " + fee); System.out.println("Hostel (declared): " + hostel); }}Fee (computed): 5637928449805158102 Hostel (declared): 1
What this code does
ObjectStreamClass.lookup(...)describes how a class is serialized;getSerialVersionUID()returns the number Java writes for it.Feedeclares nothing, so Java computes a long number from its details; that number may differ with another compiler.Hosteldeclares1L, so Java uses exactly 1 everywhere.
If the class declares it, Java uses that number as it is and never computes one. The number changes only when you change it yourself. You can see the value a class uses with ObjectStreamClass.lookup(MyClass.class).getSerialVersionUID(). The computed number is long and random-looking, it is easy to change by accident, and the serialization specification warns that it can differ between compilers for the same source code.
Compatible and incompatible changes
With the same serialVersionUID, Java tries hard to read old data into the new class. Some changes work and some do not, and Java decides field by field.
Example 3 · Same declared version: adding fields is fine
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.ObjectInputStream;import java.io.Serializable;import java.util.Base64;
class Student implements Serializable { private static final long serialVersionUID = 1L; String name; int roll; String email; // new in version 2 int year; // new in version 2
Student(String name, int roll) { this.name = name; this.roll = roll; }}
public class CompatibleChangeDemo { // Saved by version 1: serialVersionUID = 1L, fields name and roll only static final String SAVED_BY_V1 = "rO0ABXNyAAdTdHVkZW50AAAAAAAAAAECAAJJAARyb2xsTAAEbmFtZXQAEkxqYXZhL2xhbmcvU3RyaW5nO3hwAAAADHQABVByaXlh";
public static void main(String[] args) throws IOException, ClassNotFoundException { byte[] bytes = Base64.getDecoder().decode(SAVED_BY_V1); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { Student s = (Student) in.readObject(); System.out.println("Loaded: " + s.name + ", roll " + s.roll); System.out.println("New fields: email=" + s.email + ", year=" + s.year); } }}Loaded: Priya, roll 12 New fields: email=null, year=0
What this code does
- Both versions declare
serialVersionUID = 1L, so the version check passes and Java matches the fields by name. nameandrollcome from the file. The new fieldsemailandyearare not in the file, so they get the defaultsnulland0.
Example 4 · Changing a field's type is incompatible
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InvalidClassException;import java.io.ObjectInputStream;import java.io.Serializable;import java.util.Base64;
// Version 2: same serialVersionUID, but roll changed from int to Stringclass Student implements Serializable { private static final long serialVersionUID = 1L; String name; String roll; // was: int roll
Student(String name, String roll) { this.name = name; this.roll = roll; }}
public class TypeChangeDemo { // Saved by version 1: serialVersionUID = 1L, String name and int roll static final String SAVED_BY_V1 = "rO0ABXNyAAdTdHVkZW50AAAAAAAAAAECAAJJAARyb2xsTAAEbmFtZXQAEkxqYXZhL2xhbmcvU3RyaW5nO3hwAAAADHQABVByaXlh";
public static void main(String[] args) throws IOException, ClassNotFoundException { byte[] bytes = Base64.getDecoder().decode(SAVED_BY_V1); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { Student s = (Student) in.readObject(); System.out.println("Loaded " + s.name); } catch (InvalidClassException e) { System.out.println("Cannot load: " + e.getMessage()); } }}Cannot load: Student; incompatible types for field roll
What this code does
- The version numbers match, but the file has
rollas anintand the class now has it as aString. - Java cannot turn one into the other, so it throws
InvalidClassExceptionwith the message "incompatible types for field roll". - To change a type safely, add a new field with a new name and fill it from the old value in
readObject, or move to a text format.
- Compatible: adding a field (old data gives it the default
0,falseornull) and adding or removing methods. An old program reading new data ignores fields it does not know. - Loads, but with care: removing a field or making it
transient. New code skips the saved value, but an older program reading new files gets a default for that field, so the serialization specification lists this as an incompatible change. - Incompatible: changing a field's type, such as
int rolltoString roll(InvalidClassException: ...; incompatible types for field roll), and moving the class to another package or renaming it (ClassNotFoundException). - Also incompatible: moving a class up or down the class hierarchy, or turning a serializable class into one that is not.
Declaring serialVersionUID explicitly
Declare it in every serializable class, as private static final long serialVersionUID = 1L;. Since Java 14 you can put @Serial (from java.io) on it, so the compiler checks that the name and type are right.
class Student implements Serializable { @Serial private static final long serialVersionUID = 1L;
String name; int roll;}Example 5 · Raising the version on purpose rejects old data
import java.io.ByteArrayInputStream;import java.io.IOException;import java.io.InvalidClassException;import java.io.ObjectInputStream;import java.io.Serial;import java.io.Serializable;import java.util.Base64;
// Version 3: the format changed a lot, so the version number was raised on purposeclass Student implements Serializable { @Serial private static final long serialVersionUID = 2L; // was 1L
String fullName; String rollCode;
Student(String fullName, String rollCode) { this.fullName = fullName; this.rollCode = rollCode; }}
public class DeclaredVersionDemo { // Saved by version 1: serialVersionUID = 1L static final String SAVED_BY_V1 = "rO0ABXNyAAdTdHVkZW50AAAAAAAAAAECAAJJAARyb2xsTAAEbmFtZXQAEkxqYXZhL2xhbmcvU3RyaW5nO3hwAAAADHQABVByaXlh";
public static void main(String[] args) throws IOException, ClassNotFoundException { byte[] bytes = Base64.getDecoder().decode(SAVED_BY_V1); try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(bytes))) { in.readObject(); } catch (InvalidClassException e) { System.out.println("Old file rejected: " + e.getMessage()); System.out.println("Starting with an empty student list"); } }}Old file rejected: Student; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2 Starting with an empty student list
What this code does
- The class was redesigned (
fullName,rollCode), so the author changedserialVersionUIDfrom1Lto2L. - Old files now fail with a clear message showing 1 and 2, and the program can start fresh instead of loading half-empty objects.
@Serialmakes the compiler check that the field is declared correctly; it does not change the value.
Keep the number the same for compatible changes, so old files keep loading. Raise it on purpose (1L to 2L) only when old data must be refused, for example after a big redesign. Then old files fail fast with a clear InvalidClassException instead of loading into wrong fields.
The Java compiler can remind you: javac -Xlint:serial Student.java prints the warning "serializable class Student has no definition of serialVersionUID".
Fix the error
Fix the version number
student.ser was saved when the class declared 1L. Pick the line that lets the old file load.
A teammate raised the number to 2L while editing the class.
Error
Exception in thread "main" java.io.InvalidClassException: Student; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2 at java.base/java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:597)
serialVersionUID (Practice 4 does exactly this).Next step
Check your understanding
12 quick questions