Home  >  Article  >  Java  >  What is the process of java serialization and deserialization?

What is the process of java serialization and deserialization?

王林
王林Original
2024-04-15 18:06:011140browse

Java serialization and deserialization involves the following steps: Writing a class that implements the Serializable interface into a stream (serialization). Read (deserialize) the object from the stream.

What is the process of java serialization and deserialization?

Java serialization and deserialization process

Serialization

  1. Write an implementation The class with Serializable interface.
  2. Create an ObjectOutputStream object and associate it with a file or byte stream.
  3. Use the ObjectOutputStream.writeObject() method to write objects to the stream.

Sample code:

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

public class Employee implements Serializable {
    private String name;
    private int age;

    // 省略getter和setter方法

    public static void main(String[] args) {
        Employee employee = new Employee("John", 30);
        
        try (ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("employee.txt"))) {
            out.writeObject(employee);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Deserialization

  1. Create an ObjectInputStream object and associate it with a file or byte stream.
  2. Use the ObjectInputStream.readObject() method to read the object.

Sample code:

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

public class DeserializeEmployee {
    public static void main(String[] args) {
        try (ObjectInputStream in = new ObjectInputStream(new FileInputStream("employee.txt"))) {
            Employee employee = (Employee) in.readObject();
            System.out.println(employee.getName() + ", " + employee.getAge());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Notes:

  • Only implements Serializable Only interface classes can be serialized.
  • The order of serialization and deserialization must be consistent.
  • The structure of the class cannot be changed between serialization and deserialization.
  • Serializing objects can be slow, especially for large objects.

The above is the detailed content of What is the process of java serialization and deserialization?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn