Java Topic

Java Serialization and Deserialization

Serialization and deserialization are fundamental concepts in Java used to convert objects into a format that can be easily stored or transmitted and then reconstruct those objects later. These processes are critical for saving object states, data exchange, and communication in distributed systems.

1. Serialization

Serialization is the process of converting a Java object into a byte stream. This byte stream can then be saved to a file, sent over a network, or otherwise stored. Java provides built-in support for serialization via the java.io.Serializable interface.

Steps to Serialize an Object:

  • Implement Serializable Interface: The class of the object must implement the Serializable interface. This is a marker interface with no methods.
  • Use ObjectOutputStream: Use the ObjectOutputStream class to write the object to a stream.

Example:

import java.io.Serializable;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;

public class Person implements Serializable {

    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
}

public class SerializationExample {
    public static void main(String[] args) {
        try {
            Person person = new Person("John Doe", 30);
            FileOutputStream fileOut = new FileOutputStream("person.ser");
            ObjectOutputStream out = new ObjectOutputStream(fileOut);
            out.writeObject(person);
            out.close();
            fileOut.close();
            System.out.println("Serialized data is saved in person.ser");
        } catch (IOException i) {
            i.printStackTrace();
        }
    }
}

2. Deserialization

Deserialization is the process of converting a byte stream back into a Java object. The byte stream is read from a file or network, and an object is reconstructed from it.

Steps to Deserialize an Object:

  • Use ObjectInputStream: Use the ObjectInputStream class to read the object from a stream.
  • Cast the Object: Cast the deserialized object to its original type.

Example:

import java.io.ObjectInputStream;
import java.io.FileInputStream;

public class DeserializationExample {
    public static void main(String[] args) {
        Person person = null;
        try {
            FileInputStream fileIn = new FileInputStream("person.ser");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            person = (Person) in.readObject();
            in.close();
            fileIn.close();
            System.out.println("Deserialized Person...
" + "Name:" + person.getName() + " Age:" + person.getAge());
        } catch (IOException i) {
            i.printStackTrace();
        } catch (ClassNotFoundException c) {
            System.out.println("Person class not found");
            c.printStackTrace();
        }
    }
}

3. Important Points

  • serialVersionUID: It is a unique identifier for each serializable class. It is used to ensure that a loaded class corresponds exactly to the serialized object. If the serialVersionUID of the class does not match the one used during serialization, an InvalidClassException will be thrown.
  • Serializable Fields: Only fields that are marked as transient will not be serialized. This is useful for excluding sensitive or unnecessary data from serialization.
  • Security Considerations: Deserialization can be a security risk if the byte stream comes from an untrusted source. Always validate and sanitize the input to avoid security vulnerabilities.

Comments (0)

No comments yet. Be the first to comment!

LecturreAI Assistant

Hello! I'm LecturreAI

What would you like to learn today?