LearnFrenzy
Sign in Take a free test

Serialization · Serialization Programs · Question 3

Adding a field without breaking old saved data in Java Solution, output & explanation

  • Program
  • Hard
  • 0 comments
  • Answer explained
  • Moderated community
Question 3 Back to Exercise

Simulate class evolution: data saved by "version 1" of a class (name, age) is read by a class with the same serialVersionUID and an extra email field. Show that the new field arrives as null and use readObject to supply a sensible default.

Solution
Main.java
import java.io.*;

class MemberV1 implements Serializable {
    private static final long serialVersionUID = 7L;
    String name; int age;
    MemberV1(String n, int a) { name = n; age = a; }
}

class MemberV2 implements Serializable {
    private static final long serialVersionUID = 7L;     // same version: compatible change
    String name; int age;
    String email;                                         // NEW field

    @Serial private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
        in.defaultReadObject();
        if (email == null) email = name.toLowerCase() + "@unknown.lf";   // default for old data
    }
}

public class Main {
    public static void main(String[] args) throws Exception {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (ObjectOutputStream out = new ObjectOutputStream(bytes)) { out.writeObject(new MemberV1("Asha", 26)); }

        // Simulate "upgrading the class": rename MemberV1 to MemberV2 inside the saved bytes (same length).
        // The stream still describes only the OLD fields (name, age); MemberV2 has an extra field.
        byte[] data = bytes.toByteArray();
        byte[] oldName = "MemberV1".getBytes(java.nio.charset.StandardCharsets.UTF_8);
        for (int i = 0; i + oldName.length <= data.length; i++) {
            if (java.util.Arrays.equals(data, i, i + oldName.length, oldName, 0, oldName.length)) { data[i + 7] = '2'; break; }
        }
        try (ObjectInputStream in = new ObjectInputStream(new ByteArrayInputStream(data))) {
            MemberV2 m = (MemberV2) in.readObject();
            System.out.println(m.name + " " + m.age + " " + m.email);
        }
    }
}

Output Verified by compiling and running

Asha 26 asha@unknown.lf

With a matching serialVersionUID, adding a field is a compatible change: old data loads and the new field is null, which readObject replaces with a default. (Renaming the class inside the bytes only simulates deploying a new version of the class within one program.)

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links