Java -- a detailed explanation of serialization flow

Java -- a detailed explanation of serialization flow

Blog description

The information involved in this article comes from Internet collation and personal summary, which means personal learning and experience summary. If there is any infringement, please contact me to delete, thank you!

Explain

Java provides a mechanism for object serialization. An object can be represented by a sequence of bytes, which contains information such as the data of the object, the type of the object and the properties stored in the object. After the byte sequence is written out to the file, it is equivalent to persistently storing the information of an object in the file.

On the contrary, the byte sequence can also be read from the file, reconstruct the object, and deserialize it. Object data, object type, and data information stored in the object can be used to create objects in memory

Serialization flow diagram

ObjectOutputStream class

java.io.ObjectOutputStream class, which writes out the original data types of Java objects to files to realize the persistent storage of objects.

Construction method

  • public ObjectOutputStream(OutputStream out): creates an ObjectOutputStream that specifies the OutputStream.

For example, the code is as follows:

FileOutputStream fileOut = new FileOutputStream("employee.txt");
ObjectOutputStream out = new ObjectOutputStream(fileOut);

Serialization operation

  1. To serialize an object, two conditions must be met:
  • This class must implement the java.io.Serializable interface, which is a tag interface. A class that does not implement this interface will not serialize or deserialize any state, and will throw a NotSerializableException.
  • All properties of the class must be serializable. If there is a property that does not need to be serializable, it must be marked transient, decorated with the transient keyword.
Code
/**
 * @author Person
 * @date 2020/4/24 11:40 Afternoon
 */
public class Person implements java.io.Serializable{
    public String name;
    public String address;
    public transient int age; // transient decorated member, not serialized
    public void addressCheck() {
        System.out.println("Address  check : " + name + " -- " + address);
    }
}

demo

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

/**
 * @author SerializeDome
 * @date 2020/4/24 11:42 Afternoon
 */
public class SerializeDome {
    public static void main(String[] args) {
        Person p = new Person();
        p.name = "hello";
        p.address = "Beijing";
        p.age = 20;

        try{
            ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream("person.txt"));
            out.writeObject(p);
            out.close();
            System.out.println("serialize");
        }catch (IOException i){
            i.printStackTrace();
        }
    }
}

ObjectInputStream class

ObjectInputStream deserializes the stream, restoring the original data previously serialized with ObjectOutputStream to an object.

Construction method

  • public ObjectInputStream(InputStream in): creates an ObjectInputStream that specifies an InputStream.

Deserialization operation

Code
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

/**
 * @author DeserializeDemo
 * @date 2020/4/24 11:52 Afternoon
 */
public class DeserializeDemo {
    public static void main(String [] args)   {
        Person e = null;
        try {
            // Create deserialization stream
            FileInputStream fileIn = new FileInputStream("person.txt");
            ObjectInputStream in = new ObjectInputStream(fileIn);
            // Read an object
            e = (Person) in.readObject();
            // Release resources
            in.close();
            fileIn.close();
        }catch(IOException i) {
            // Catch other exceptions
            i.printStackTrace();
            return;
        }catch(ClassNotFoundException c)  {
            // Catch class cannot find exception
            System.out.println("Person class not found");
            c.printStackTrace();
            return;
        }
        // No exception, direct printout
        System.out.println("Name: " + e.name);
        System.out.println("Address: " + e.address);
        System.out.println("age: " + e.age);
    }
}

Result

Be careful

For a JVM to deserialize an object, it must be a class that can find the class file. If the class file of the class cannot be found, a ClassNotFoundException exception is thrown.

In addition, when the JVM deserializes the object, it can find the class file, but the class file has been modified after the object is serialized, so the deserialization operation will fail, and an InvalidClassException exception exception will be thrown.

The reasons for this exception are as follows:

  • The serial version number of the class does not match the version number of the class descriptor read from the stream
  • This class contains an unknown data type
  • This class has no accessible parameterless construction method

The Serializable interface provides a serial version number for the class to be serialized. serialVersionUID the purpose of this version number is to verify that the serialized object and the corresponding class are version matched.

// Add serial version number
private static final long serialVersionUID = 1L;

Thank

Black horse programmer

And the industrious self

Tags: Java jvm

Posted on Fri, 24 Apr 2020 09:35:55 -0700 by dkode