Demystifying Java Serialization
Introduction
Serialization in Java is a mechanism of converting an object into a byte stream so that it can be saved to a file, transmitted over a network, or stored in a database. The reverse process, converting the byte stream back into an object, is known as deserialization.
Why Use Serialization?
Serialization is used for:
How Serialization Works in Java?
Serialization in Java is achieved using the java.io.Serializable interface. This is a marker interface, meaning it does not contain any methods but indicates that a class can be serialized.
Example of Serialization
import java.io.*;
class Person implements Serializable {
private static final long serialVersionUID = 1L; // Recommended for version control
String name;
int age;
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class SerializationDemo {
public static void main(String[] args) {
try {
Person p = new Person("John", 30);
FileOutputStream fileOut = new FileOutputStream("person.ser");
ObjectOutputStream out = new ObjectOutputStream(fileOut);
out.writeObject(p);
out.close();
fileOut.close();
System.out.println("Object serialized and saved in person.ser");
} catch (IOException e) {
e.printStackTrace();
}
}
}
Explanation:
Example of Deserialization
import java.io.*;
public class DeserializationDemo {
public static void main(String[] args) {
try {
FileInputStream fileIn = new FileInputStream("person.ser");
ObjectInputStream in = new ObjectInputStream(fileIn);
Person p = (Person) in.readObject();
in.close();
fileIn.close();
System.out.println("Deserialized Person: " + p.name + ", Age: " + p.age);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
}
Explanation:
Recommended by LinkedIn
Transient Keyword
If you do not want to serialize a particular field, use the transient keyword.
class Employee implements Serializable {
String name;
transient int salary; // Will not be serialized
public Employee(String name, int salary) {
this.name = name;
this.salary = salary;
}
}
SerialVersionUID
The serialVersionUID is used for version control of serialized objects. If not specified, Java generates one dynamically, which may cause issues if the class changes.
private static final long serialVersionUID = 1L;
Drawbacks of Serialization
Image Representation
Conclusion
Serialization in Java is a powerful mechanism to save and transfer objects. By implementing Serializable, using transient for sensitive data, and managing serialVersionUIDDevelopers can effectively serialize and deserialize objects in Java.
___
Happy coding!
Follow my Instagram page — Programming_Pulse for daily programming tips and insights!