Unlock Java Serialization: Why Serializable Matters and How to Master It

This article dives deep into Java's serialization mechanism, explaining the theory behind the Serializable interface, demonstrating practical examples with code, exploring the impact of static and transient fields, comparing Serializable with Externalizable, and clarifying the role of serialVersionUID in version compatibility.

Java Backend Technology
Java Backend Technology
Java Backend Technology
Unlock Java Serialization: Why Serializable Matters and How to Master It

01. Theory

Java serialization was introduced in JDK 1.1 to convert objects into byte arrays for storage or transmission, and later reconstruct them back into objects. The idea is to "freeze" an object's state during serialization and "thaw" it during deserialization.

The Serializable interface is empty; it merely marks a class as eligible for serialization.

public interface Serializable {
}

02. Practical Example

Define a simple class with two fields and generate getters/setters:

class Wanger {
    private String name;
    private int age;
    public String getName() { return name; }
    public void setName(String name) { this.name = name; }
    public int getAge() { return age; }
    public void setAge(int age) { this.age = age; }
}

Use ObjectOutputStream to write an instance to a file (serialization) and ObjectInputStream to read it back (deserialization):

public class Test {
    public static void main(String[] args) {
        Wanger wanger = new Wanger();
        wanger.setName("王二");
        wanger.setAge(18);
        System.out.println(wanger);
        try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("chenmo"))) {
            oos.writeObject(wanger);
        } catch (IOException e) { e.printStackTrace(); }
        // modify static field after serialization
        Wanger.pre = "不沉默";
        try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(new File("chenmo")))) {
            Wanger wanger1 = (Wanger) ois.readObject();
            System.out.println(wanger1);
        } catch (IOException | ClassNotFoundException e) { e.printStackTrace(); }
    }
}

Running this shows that static fields are not serialized (their value changes after deserialization) and transient fields are omitted (they become null or default values).

03. Important Notes

Fields marked static or transient are not serialized. Static fields belong to the class, not the object state; transient fields are intentionally excluded, resetting to default values upon deserialization.

04. Advanced Topic: Externalizable

Besides Serializable, Java provides Externalizable, which requires implementing writeExternal and readExternal and a public no‑arg constructor.

class Wanger implements Externalizable {
    private String name;
    private int age;
    public Wanger() {}
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(name);
        out.writeInt(age);
    }
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = (String) in.readObject();
        age = in.readInt();
    }
}

If the no‑arg constructor is missing, deserialization fails with InvalidClassException.

05. SerialVersionUID

The serialVersionUID field identifies a class version. Mismatched IDs between the serialized stream and the current class cause InvalidClassException. You can define it explicitly, let the compiler generate a default (1L), or rely on the IDE’s random generation (which may change across builds).

private static final long serialVersionUID = -2095916884810199532L;

Changing the ID after objects have been persisted makes them unreadable.

06. Summary

Java serialization is a powerful feature but requires careful handling of static/transient fields, proper implementation of Serializable or Externalizable, and consistent serialVersionUID to ensure reliable deserialization.

Serialization before: Wanger{name=王二,age=18} Serialization after: Wanger{name=王二,age=18}
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

javaserializationserializablestatictransientExternalizableObjectInputStreamObjectOutputStream
Java Backend Technology
Written by

Java Backend Technology

Focus on Java-related technologies: SSM, Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading. Occasionally cover DevOps tools like Jenkins, Nexus, Docker, and ELK. Also share technical insights from time to time, committed to Java full-stack development!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.