Lesson 45: Object Serialization and Deserialization
Serialization is the process of converting an object's state into a sequence of bytes (a stream). This stream can then be saved to a file or transmitted across a network.
Deserialization is the reverse process: reconstructing the object from the stream of bytes.
1. Making a Class Serializable
For an object to be serializable, its class must implement the marker interface java.io.Serializable.
java import java.io.Serializable;
public class Employee implements Serializable { // Fields must also be serializable, or marked 'transient' private String name; private int id;
// transient fields are ignored during serialization
private transient String password;
// Best practice: add a unique ID for version control
private static final long serialVersionUID = 1L;
}
2. Serialization (Writing the Object)
We use ObjectOutputStream, which must wrap a byte stream (like FileOutputStream).
java // Output Stream try (FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream objOut = new ObjectOutputStream(fileOut)) {
Employee emp = new Employee("John", 101);
objOut.writeObject(emp); // Write the entire object to the stream
System.out.println("Employee object serialized.");
} catch (IOException i) { i.printStackTrace(); }
3. Deserialization (Reading the Object)
We use ObjectInputStream and must cast the read Object back to the specific class type.
java // Input Stream try (FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream objIn = new ObjectInputStream(fileIn)) {
Employee e = (Employee) objIn.readObject(); // Read and cast
System.out.println("Employee deserialized: " + e.getName());
} catch (IOException | ClassNotFoundException e) { e.printStackTrace(); }