In advanced Java, serialization and deserialization are processes to save and restore the state of an object, making it possible to store objects in files or databases, or transfer them over a network. Here’s a breakdown of these concepts and their application
1️⃣ Serialization
Serialization is the process of converting an object into a stream of bytes. This byte stream can be saved to a file, sent over a network, or stored in a database. In Java, the Serializable interface is used to indicate that a class can be serialized.
✍ Steps to serialize an object:
▶️ Implement the Serializable interface.
▶️ Use ObjectOutputStream and FileOutputStream to write the object to a file or output stream.
▶️ Call the writeObject() method on ObjectOutputStream.
?Code Example:
import java.io.FileOutputStream; import java.io.ObjectOutputStream; import java.io.Serializable; class Employee implements Serializable { private static final long serialVersionUID = 1L; String name; int id; public Employee(String name, int id) { this.name = name; this.id = id; } } public class SerializeDemo { public static void main(String[] args) { Employee emp = new Employee("John Doe", 101); try (FileOutputStream fileOut = new FileOutputStream("employee.ser"); ObjectOutputStream out = new ObjectOutputStream(fileOut)) { out.writeObject(emp); System.out.println("Serialized data is saved in employee.ser"); } catch (Exception e) { e.printStackTrace(); } } }
Here, employee.ser is a serialized file that stores the object’s byte stream.
2️⃣ Deserialization
Deserialization is the reverse process, where the byte stream is converted back into a copy of the original object. This enables you to recreate the object’s state after it’s been stored or transferred.
✍ Steps to deserialize an object:
▶️ Use ObjectInputStream and FileInputStream to read the object from the file or input stream.
▶️ Call the readObject() method on ObjectInputStrea
?Code Example:
import java.io.FileInputStream; import java.io.ObjectInputStream; public class DeserializeDemo { public static void main(String[] args) { Employee emp = null; try (FileInputStream fileIn = new FileInputStream("employee.ser"); ObjectInputStream in = new ObjectInputStream(fileIn)) { emp = (Employee) in.readObject(); System.out.println("Deserialized Employee..."); System.out.println("Name: " + emp.name); System.out.println("ID: " + emp.id); } catch (Exception e) { e.printStackTrace(); } } }
This will retrieve the object’s original state, allowing access to its fields as they were before serialization.
3️⃣ Advanced Serialization Topics
▶️ Custom Serialization: Override writeObject() and readObject() for customized serialization.
▶️ Externalizable Interface: Provides full control over serialization, requiring the implementation of writeExternal() and readExternal() methods.
▶️ Transient Fields: Use the transient keyword to avoid serializing specific fields (e.g., sensitive data like passwords).
✍ Advantages of Serialization:
▶️ Allows saving the state of an object for future use.
▶️ Facilitates the transfer of complex data objects over networks.
? Briefly Explain Code Example
import java.io.*; class Student implements Serializable { private static final long serialVersionUId = 1l; private String name ; private int age; private String Address; public Student(String name,int age,String Address){ this.name = name; this.age = age; this.Address = Address; } public void setName(String name){ this.name = name; } public void setAge(int age){ this.age = age; } public void setAddress(String Address){ this.Address = Address; } public String getName(){ return name; } public String getAddress(){ return Address; } public int getAge(){ return age; } public String toString(){ return ("Student name is "+this.getName()+", age is "+this.getAge()+", and address is "+this.getAddress()); } } public class JAVA3_Serialization { // when you implement Serializable then you must be write a serialVersionUId because when it serialise and deserialize it uniquely identify in the network // when u update ur object or anything then you have to update the serialVersionUId increment . // private static final long serialVersionUId = 1l; // transient int x ; // If you do not want a particular value to serialise and Deserialize. // the value x, when you don't serialise and Deserialize Then transient you used. public static void main(String[] args) { Student student = new Student("kanha",21,"angul odisha"); String filename = "D:\Advance JAVA\CLS3 JAVA\Test.txt"; // store the data in this location FileOutputStream fileOut = null; // write file ObjectOutputStream objOut = null; // create object //Serialization try { fileOut = new FileOutputStream(filename); objOut = new ObjectOutputStream(fileOut); objOut.writeObject(student); objOut.close(); fileOut.close(); System.out.println("Object has been serialise =\n"+student); } catch (IOException ex){ System.out.println("error will occure"); } //Deserialization FileInputStream fileIn = null; ObjectInputStream objIn = null; try { fileIn = new FileInputStream(filename); objIn = new ObjectInputStream(fileIn); Student object =(Student) objIn.readObject(); System.out.println("object has been Deserialization =\n"+object); objIn.close(); fileIn.close(); } catch (IOException e) { throw new RuntimeException(e); } catch (ClassNotFoundException e) { throw new RuntimeException(e); } } }
✍ Key Notes:
▶️ Only non-static and non-transient data members are serialized by default.
▶️ Serializable objects must ensure compatibility between versions if the class is modified after serialization.
For more insights, feel free to mention your GitHub for in-depth examples and code samples! Let me know if you'd like any specific adjustments.
GitHub - https://github.com/Prabhanjan-17p
The above is the detailed content of Serialization and Deserialization In Java. For more information, please follow other related articles on the PHP Chinese website!