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.
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.
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.
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.
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.
class User implements Serializable {
private static final long serialVersionUID = 1L;
}
Serialization Exceptions
Serialization commonly involves IOException and deserialization can also throw ClassNotFoundException.
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.