Java Serialization

Serialization converts a Java object into a byte stream so it can be saved or transferred. Deserialization converts the byte stream back into an object.

Implement Serializable

A class must implement the Serializable interface to allow its objects to be serialized.

Java
A simple serializable class.
import java.io.Serializable;

class User implements Serializable {
    private String name;
    private int age;

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

Serialize an Object

ObjectOutputStream writes an object to a file or another output stream.

Java
Writing an object to a file.
try (ObjectOutputStream out = new ObjectOutputStream(
        new FileOutputStream("user.ser"))) {
    out.writeObject(new User("John", 25));
}

Deserialize an Object

ObjectInputStream reads the serialized data and reconstructs the object.

Java
Reading an object from a file.
try (ObjectInputStream in = new ObjectInputStream(
        new FileInputStream("user.ser"))) {
    User user = (User) in.readObject();
}

Transient Fields

A transient field is skipped during serialization. It is useful for temporary or sensitive values that should not be serialized.

Java
The password will not be serialized.
class User implements Serializable {
    String username;
    transient String password;
}

serialVersionUID

serialVersionUID identifies the version of a Serializable class and helps detect incompatible class changes during deserialization.

Java
Defining a serialVersionUID.
class User implements Serializable {
    private static final long serialVersionUID = 1L;
}

Serialization Exceptions

Serialization commonly involves IOException and deserialization can also throw ClassNotFoundException.

Java
Handling common exceptions.
try {
    // serialization or deserialization
} catch (IOException e) {
    e.printStackTrace();
} catch (ClassNotFoundException e) {
    e.printStackTrace();
}

Serialization Best Practices

Use serialVersionUID, mark sensitive or temporary fields as transient, close streams with try-with-resources, and avoid deserializing untrusted data.

Java Serialization Summary

Serializable marks classes for serialization, ObjectOutputStream writes objects, ObjectInputStream reads objects, transient excludes fields, and serialVersionUID helps maintain class compatibility.