Java.Serialization.Describe the serialization/deserialization process using Serializable.

🔹 1. Mark the Class as Serializable

To make a class eligible for serialization:

import java.io.Serializable;

public class Person implements Serializable {
    private static final long serialVersionUID = 1L; // Optional but recommended

    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

✅ This tells Java: “You can save and restore objects of this class.”

🔹 2. Serialize the Object (Write to a File/Stream)

You use ObjectOutputStream to write the object to a file as a byte stream:

import java.io.*;

Person p = new Person("Stanley", 33);

try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.ser"))) {
    out.writeObject(p);
}

🧠 Java will:

  • Check that Person implements Serializable
  • Write the object once, even if referenced multiple times
  • Store the object structure, field values, and object graph

🔹 3. Deserialize the Object (Read from a File/Stream)

To reconstruct the object later:

Person loaded;

try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("person.ser"))) {
    loaded = (Person) in.readObject();
}
System.out.println(loaded.name + ", " + loaded.age); // Stanley, 33

🧠 Java will:

  • Read the byte stream
  • Use the serialVersionUID to ensure class compatibility
  • Reconstruct the object in new heap memory
  • Restore all non-transient fields

🔑 What Happens Internally

StepInternal Behavior
Write (writeObject)Object graph is traversed, serialized, and referenced via ID
StoreFields, type info, reference map are written to the file
Read (readObject)Objects are reconstructed; shared references are preserved
== between shared objectsStill true, because Java reuses deserialized instances

⚠️ Special Cases

FeatureBehavior
transient fieldsNot saved to file
static fieldsNot saved (belong to class, not instance)
serialVersionUID mismatchThrows InvalidClassException
Not implementing SerializableThrows NotSerializableException

🔥 Bonus: Add transient to skip fields

transient String password;

This will not be saved to the file.

🧪 Full Example (Mini Demo)

// Serializable class
public class Person implements Serializable {
    private static final long serialVersionUID = 1L;
    String name;
    int age;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
}

// Save
Person p = new Person("Stanley", 33);
ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("p.ser"));
out.writeObject(p);
out.close();

// Load
ObjectInputStream in = new ObjectInputStream(new FileInputStream("p.ser"));
Person p2 = (Person) in.readObject();
in.close();

System.out.println(p2.name + ", " + p2.age); // Stanley, 33

🧵 TL;DR

StepToolDescription
1. Mark classimplements SerializableMakes it eligible for serialization
2. SaveObjectOutputStream.writeObject(obj)Writes object to stream/file
3. LoadObjectInputStream.readObject()Reads and reconstructs the object
Version controlserialVersionUIDEnsures class compatibility
This entry was posted in Без рубрики. Bookmark the permalink.

Leave a Reply

Your email address will not be published.