Home > Java > javaTutorial > body text

Implementation methods of serialization and deserialization in Java language

WBOY
Release: 2023-06-10 21:33:42
Original
795 people have browsed it

The Java language is an object-oriented programming language that is platform-independent, easy to learn and use, and highly reliable. Among them, object serialization and deserialization is a very important function in the Java language, which can easily transmit or store objects in different JVMs. This article will introduce the implementation methods of Java language serialization and deserialization.

1. The concept of serialization

Serialization refers to the process of converting objects into byte sequences so that they can be transmitted or stored on the network. The serialization process can convert Java objects into a common format, such as XML, JSON, binary stream, etc., for transmission and processing on different platforms. In the Java language, serialization can be implemented using the Java.io.Serializable interface.

2. Java.io.Serializable interface

The Java.io.Serializable interface is a marking interface provided by the Java language, used to mark a class that can be serialized. Only classes that implement this interface can perform serialization and deserialization operations. This interface does not implement any methods, but serves as a marker to tell the JVM that this class is serializable.

The class that implements the Java.io.Serializable interface must meet the following conditions:
1. The class must be serializable, that is, its status can be written to the byte stream.
2. This class must have a parameterless constructor.
3. All non-static member variables of this class must be serializable.

For example, the following is an example of a class that implements the Java.io.Serializable interface:

import java.io.Serializable;

public class Person implements Serializable {
    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; }
}
Copy after login

3. Serialization implementation methods

The Java language provides two Serialization implementation methods: Java.io.ObjectOutputStream class and Java.io.ByteArrayOutputStream class.

  1. Java.io.ObjectOutputStream class

The Java.io.ObjectOutputStream class is a serialization class provided by the Java language. This class provides methods to serialize Java objects into a stream of bytes and the possibility to write these bytes into an OutputStream. The following is an example of a method that serializes a Person object into a byte stream and writes it to a file:

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

public class SerializeDemo {
    public static void main(String[] args) {
        Person person = new Person("Tom", 20);

        try {
            FileOutputStream fos = new FileOutputStream("person.ser");
            ObjectOutputStream oos = new ObjectOutputStream(fos);

            oos.writeObject(person);

            oos.close();
            fos.close();

            System.out.println("Person对象已经序列化到person.ser中。");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login
  1. Java.io.ByteArrayOutputStream class

Java.io. The ByteArrayOutputStream class is a class provided by the Java language for serialization. This class provides methods to serialize Java objects into byte arrays and the possibility to store these bytes into a ByteArrayOutputStream. The following is an example of a method that serializes a Person object into a byte stream and stores it in a byte array:

import java.io.ByteArrayOutputStream;
import java.io.ObjectOutputStream;

public class SerializeDemo {
    public static void main(String[] args) {
        Person person = new Person("Tom", 20);

        try {
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(bos);

            oos.writeObject(person);

            byte[] byteArray = bos.toByteArray();

            oos.close();
            bos.close();

            System.out.println("Person对象已经序列化到字节数组中。");

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login

4. Deserialization implementation methods

The Java language provides two Three deserialization implementation methods: Java.io.ObjectInputStream class and Java.io.ByteArrayInputStream class.

  1. Java.io.ObjectInputStream class

The Java.io.ObjectInputStream class is a deserialization class provided by the Java language. This class provides methods to read bytes from the InputStream and deserialize them into Java objects. The following is an example of a method that reads a byte stream from a file and deserializes it into a Person object:

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

public class DeserializeDemo {
    public static void main(String[] args) {
        try {
            FileInputStream fis = new FileInputStream("person.ser");
            ObjectInputStream ois = new ObjectInputStream(fis);

            Person person = (Person) ois.readObject();

            ois.close();
            fis.close();

            System.out.println("从person.ser文件中反序列化出了一个Person对象。");
            System.out.println("Person对象的name是:" + person.getName());
            System.out.println("Person对象的age是:" + person.getAge());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login
  1. Java.io.ByteArrayInputStream class

Java. The io.ByteArrayInputStream class is a class provided by the Java language for deserialization. This class provides methods to read bytes from a byte array and deserialize them into Java objects. The following is an example of a method to deserialize a byte array into a Person object:

import java.io.ByteArrayInputStream;
import java.io.ObjectInputStream;

public class DeserializeDemo {
    public static void main(String[] args) {
        try {
            Person person = null;
            byte[] byteArray = // 从其他途径获取的Person对象的字节数组

            ByteArrayInputStream bais = new ByteArrayInputStream(byteArray);
            ObjectInputStream ois = new ObjectInputStream(bais);

            person = (Person) ois.readObject();

            ois.close();
            bais.close();

            System.out.println("从字节数组中反序列化出了一个Person对象。");
            System.out.println("Person对象的name是:" + person.getName());
            System.out.println("Person对象的age是:" + person.getAge());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
Copy after login

In short, the serialization and deserialization functions of the Java language are a very important function, which can easily convert objects in different Transfer or store in JVM. Serialization and deserialization are achieved by implementing the Java.io.Serializable interface and using the Java.io.ObjectOutputStream class and the Java.io.ObjectInputStream class. At the same time, the Java.io.ByteArrayOutputStream class and Java.io.ByteArrayInputStream class can also implement these operations.

The above is the detailed content of Implementation methods of serialization and deserialization in Java language. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!