Detailed Java serialization and deserialization

Tips before viewing:

The Eclipse version used in this article is Photon Release (4.8.0), IDEA version is ultimate 2019.1, JDK version is 1.8.0_141, and Tomcat version is 9.0.12.

1. Basic concepts

1.1 Definition

Serialization: The process of converting an object into a sequence of bytes is called serialization of the object.

Deserialization: The process of restoring a byte sequence to an object is called object deserialization.

1.2 Purpose

  1. The byte sequence of the object is permanently saved to the hard disk, usually in a file.

  2. Transfer the byte sequence of the object on the network.

2. Realize serialization and deserialization

2.1 Serialization API in JDK library

Key classes in JDK ObjectOutputStream (object output stream) with ObjectInputStream (object input stream)

ObjectOutputStream class: Write the object in binary format by using the writeObject(Object object) method.

ObjectInputStream class: read the binary stream from the input stream and convert it into an object by using the readObject() method.

2.2 Implement Serializable interface

All attributes of this object (including private attributes and the objects it references) can be serialized and deserialized to save and transfer. Fields that do not want to be serialized can be modified with transient.

Examples are as follows

Person.java that implements the Serializable interface

package testSerialize;

import java.io.Serializable;

public class Person implements Serializable {
    
    

    private static final long serialVersionUID = 1351786752651948395L;

    private String id;
    private String name;
    private transient int age;

    public String getId() {
    
    
        return id;
    }

    public void setId(String id) {
    
    
        this.id = id;
    }

    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;
    }

    @Override
    public String toString() {
    
    
        return "Person{" +
                "id='" + id + '\'' +
                ", name='" + name + '\'' +
                ", age=" + age +
                '}';
    }
}

Test class Test.java

package testSerialize;

import java.io.*;

public class Test {
    
    

    public static void main(String[] args){
    
    

        // 序列化
        Person person = new Person();
        person.setId("123456");
        person.setName("张三");
        person.setAge(18);
        // ObjectOutputStream输出流,将Person对象存储到文件中,实现序列化
        ObjectOutputStream os = null;
        try {
    
    
            os = new ObjectOutputStream(new FileOutputStream("D:test.txt"));
            os.writeObject(person);
            os.close();
        } catch (Exception e){
    
    
            e.printStackTrace();
        } finally {
    
    
            if (os != null){
    
    
                try {
    
    
                    os.close();
                } catch (Exception e){
    
    

                }
            }
        }
        System.out.println("--------------------序列化完成--------------------");

        // 反序列化
        ObjectInputStream is = null;
        try {
    
    
            is = new ObjectInputStream(new FileInputStream("D:test.txt"));
            Person p = (Person) is.readObject();
            System.out.println(p.toString());
        } catch (Exception e){
    
    
            e.printStackTrace();
        } finally {
    
    
            if (is != null){
    
    
                try {
    
    
                    is.close();
                } catch (Exception e){
    
    

                }
            }
        }
        System.out.println("--------------------反序列化完成--------------------");
    }
}

The results are as follows
Insert picture description here

Save the content of the file as serialized things that we don't understand
Insert picture description here

note

  1. The function of the Serializable interface is only to identify that our class needs to be serialized, and the Serializable interface does not provide any methods.

  2. SerialVersionUid The serialized version number is used to distinguish the version of the class we wrote, and used to determine whether the version of the class is consistent during deserialization. If it is inconsistent, an inconsistent version exception will occur.

  3. transient keyword, mainly used to ignore variables that we do not want to serialize

2.3 Implement Externalizable interface

It is a subclass of Serializable interface, what the user wants to achieve ==writeExternal()withThe readExternal() == method is used to determine how to serialize and deserialize.

Guess you like

Origin blog.csdn.net/weixin_43611145/article/details/108715676