Java serialization mechanism

1、 Why serialize?

1. Generally, Java objects can exist only when the JVM is running, that is, the life cycle of these objects will not be longer than that of the JVM. However, in real applications, it may be required to save (persist) the specified object after the JVM stops running, and re read the saved object in the future. Java object serialization can help us realize this function.

2. When transferring objects in network or process communication, we all need to use serialization to convert Java objects into byte sequences for transmission. The specific performance is to serialize objects before sending data and deserialize objects after receiving data.

2、 What is serialization?

Serialization means that Java objects that implement serialization are allowed to be converted into byte sequences. These byte sequences can be saved on disk or transmitted through the network to restore to the original objects in the future. The serialization mechanism allows objects to exist independently of the program.

Generally speaking, Java serialization refers to the process of converting Java objects into byte sequences, while Java deserialization refers to the process of restoring byte sequences into Java objects.

3、 Java serialization mechanism

1. Use serializable interface to realize serialization

In Java, only one class implements Java io. Serializable interface, then it can be serialized.

@Data
public class UserA implements Serializable {
    /**
     * 序列化ID
     */
    private static final long serialVersionUID = 1L;

    private int age;
    private static String name = "张三";

    @Override
    public String toString() {
        return "User{age=" + age + ",name=" + name + "}";
    }    
}

2. Use the externalizable interface to realize serialization

Externalizable inherits from the serializable interface. We need to override the writeexternal () and readexternal () methods to determine which information to serialize, and we must provide a public parameterless constructor.

The performance of externalizable is better than that of serializable, but it also increases the complexity.

@Data
public class UserB implements Externalizable {
    /**
     * 序列化ID
     */
    private static final long serialVersionUID = 1L;

    private int age;
    private static String name = "李四";


    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(age);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException,ClassNotFoundException {
        age = in.readInt();
    }

    @Override
    public String toString() {
        return "User{age=" + age + ",name=" + name + "}";
    }
}

3. Serialization and deserialization

By implementing the serializable interface or externalizable interface, Java objects have the qualification of serialization. How to serialize and deserialize them? Here, objectoutputstream and objectinputstream are used to serialize and deserialize objects.

    public static void main(String[] args) {
        // 序列化
        serialize();
        // 反序列化
        deserialize();
    }

    private static void serialize() {
        UserA user = new UserA();
        user.setAge(26);
        //序列化对象到文件中
        try (ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("D:\\userA"))) {
            objectOutputStream.writeObject(user);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void deserialize() {
        try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\userA"))) {
            UserA user = (UserA) objectInputStream.readObject();
            System.out.println(user);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

4、 Serialization analysis

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>