What is serialization? How to implement serialization in Java?

What is serialization? How to implement serialization in Java?

In Java programming, serialization is the process of converting an object into a stream of bytes, which can be transmitted over the network or saved to disk. Serialization saves the state of an object so that it can be recreated when needed. Java provides a set of serialization mechanisms that can make the serialization and deserialization of objects simple and convenient.

insert image description here

Basic concepts of serialization

Serialization in Java refers to the process of converting an object into a stream of bytes so that the state of the object can be saved and restored. The core of serialization is java.io.Serializablethe interface, which is a marker interface without any methods, just used to identify a class that can be serialized. If a class implements Serializablethe interface, objects of this class can be serialized into byte streams for transmission over the network or storage to disk.

The basic idea of ​​serialization is to convert an object into a set of bytes, and then write the bytes to a stream. You can use ObjectOutputStreamthe class to serialize an object, for example:

public static void serialize(Object obj, OutputStream out) throws IOException {
    
    
    ObjectOutputStream oos = new ObjectOutputStream(out);
    oos.writeObject(obj);
    oos.close();
}

The above code serializes an object into a byte stream and writes it to the output stream.

The basic idea of ​​deserialization is to read bytes from a stream and convert the bytes to objects. You can use ObjectInputStreamthe class to deserialize an object, for example:

public static Object deserialize(InputStream in) throws IOException, ClassNotFoundException {
    
    
    ObjectInputStream ois = new ObjectInputStream(in);
    Object obj = ois.readObject();
    ois.close();
    return obj;
}

The code above reads bytes from the input stream and converts the bytes into an object.

Serialization mechanism in Java

The serialization mechanism in Java is based on object streams, that is, serialization is achieved by writing objects to the stream. The object stream in Java includes ObjectOutputStreamand ObjectInputStreamtwo classes, which are used to write objects into the stream and read objects from the stream respectively.

The serialization mechanism in Java supports the following features:

  • Object reference: During serialization, the reference of the object will be serialized into an identifier, and the reference relationship of the object will be restored according to this identifier during deserialization.
  • Inheritance relationship: When serializing, the class information of the object will be serialized together, and when deserializing, the class relationship of the object will be restored according to this class information.
  • Version control: When serializing, the version number of the object will be serialized together, and when deserializing, it will judge whether it can be deserialized according to this version number. An exception is thrown if the object's version number does not match the current class version InvalidClassException.

The serialization mechanism in Java uses two methods: default serialization and custom serialization.

Default serialization refers to ObjectOutputStreamthe process of converting an object into a byte stream using a , which automatically preserves the state of the object, including all fields and references of the object. The default serialization will suffice for most cases, but custom serialization may be required in some cases.

Custom serialization refers to the manual implementation of serialization and deserialization of objects using the writeObject()and methods. readObject()Custom serialization can control the serialization process of objects, and can perform some special processing during serialization and deserialization, such as encryption, compression, verification, etc.

Serialization implementation in Java

The implementation of serialization in Java is very simple, just let the object implement Serializablethe interface. Here is a sample code:

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 int getAge() {
    
    
        return age;
    }
}

The code above defines a Personclass that implements Serializablethe interface. A object can be Personserialized into a byte stream using the following code:

Person person = new Person("张三", 20);
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(out);
oos.writeObject(person);
byte[] bytes = out.toByteArray();

The code above Personserializes an object into a byte stream and saves it into a byte array.

A byte array can be deserialized into a Personobject using the following code:

ByteArrayInputStream in = new ByteArrayInputStream(bytes);
ObjectInputStream ois = new ObjectInputStream(in);
Person person = (Person) ois.readObject();

The code above deserializes a byte array into a Personobject.

In practical applications, some special cases may be encountered, such as serializing a subclass of an object, and serializing a field of an object requires special handling, etc. Here is a sample code showing how to implement custom serialization:

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

    public Person(String name, int age) {
    
    
        this.name = name;
        this.age = age;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
    
    
        out.writeUTF(name);
        out.writeInt(age);
    }

    private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    
    
        name = in.readUTF();
        age = in.readInt();
    }

    public String getName() {
    
    
        return name;
    }

    public int getAge() {
    
    
        return age;
    }
}

The above code implements custom serialization, writes the and fields Personof the object to the stream, and restores them during deserialization.nameage

Summarize

The serialization mechanism in Java is a process of converting an object into a byte stream, so that the state of the object can be saved and restored. Java provides a set of serialization mechanisms that can make the serialization and deserialization of objects simple and convenient. The serialization mechanism in Java uses two methods: default serialization and custom serialization, and you can choose different methods to realize serialization according to the actual situation. In practical applications, some special cases may need to be considered, such as serializing a subclass of an object, special handling is required when serializing an object’s fields, etc., which can be implemented using custom serialization.

Guess you like

Origin blog.csdn.net/JasonXu94/article/details/131744937