Java serialization and deserialization

Ask for compliments and thank your boss every day.

Welcome to pay attention to the public number: in fact, it is an Aries. Dry goods continue to be updated at……

What is it

Serialization: The process of converting an object into a sequence of bytes.

Deserialization: The process of converting a sequence of bytes into an object.

The serialized byte sequence of an object contains the type information of the object, the data of the object, etc. In other words, it contains all the information describing the object, and can be “copied” from this information to create an identical object.

Two, why

So why serialize? There are two reasons

  1. Persistence: An object is a heap area stored in the JVM, but if the JVM stops running, the object does not exist. Serialization converts an object into a sequence of bytes that can be written to a disk file for persistence. In a newly opened JVM, byte sequences can be read and deserialized into objects.
  2. Network transmission: The network directly transmits data, but cannot directly transmit objects. Serialization can be performed before transmission and deserialized into objects after transmission. So all objects that can be transported over the network must be serializable.

Three, how to do

How do you serialize objects?

Java provides a mechanism for object serialization, specifying the conditions and implementation methods for the classes to implement serialized objects.

  1. Implement the Serializable interface or Externalizable interface for classes that serialize objects
  2. ObjectOutputStream and ObjectInputStream are provided by the JDK to implement serialization and deserialization

The Serializable and Externalizable interfaces are implemented to demonstrate serialization and deserialization, respectively

1. Implement the Serializable interface

public class TestBean implements Serializable {

    private Integer id;

    private String name;

    private Date date;
	// Omit getter and setter methods and toString
}
Copy the code

Serialization:

public static void main(String[] args) {
    TestBean testBean = new TestBean();
    testBean.setDate(new Date());
    testBean.setId(1);
    testBean.setName("zll1");
    // Serialize the testBean object with ObjectOutputStream and write the serialized byte sequence to test.txt
    try (FileOutputStream fileOutputStream = new FileOutputStream("D:\\test.txt");
         ObjectOutputStream objectOutputStream = new ObjectOutputStream(fileOutputStream);) {
        objectOutputStream.writeObject(testBean);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch(IOException e) { e.printStackTrace(); }}Copy the code

After execution, you can see the serialized contents in the test.txt file

Deserialization:

public static void main(String[] args) {
    try (FileInputStream fileInputStream = new FileInputStream("D:\\test.txt");
         ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream)) {
        TestBean testBean = (TestBean) objectInputStream.readObject();
        System.out.println(testBean);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch(ClassNotFoundException e) { e.printStackTrace(); }}Copy the code

The output

TestBean{id=1, name='zll1', date=Fri Nov 27 14:52:48 CST 2020}
Copy the code

Note:

  1. When an object is serialized, if its member variable is a reference type, the reference type must be serializable, otherwise an error will be reported
  2. The same object serialization into a sequence of bytes for many times, the multiple deserialized into object or a byte sequence (using the = = judgment to true) (because all object serialization to save will generate a serialized number, when serialized again go back to check whether the object has been serialized, if it is, the serialization will only output on a serialized number)
  3. If you serialize a mutable object, after you serialize it, change the value of the object’s properties, and serialize it again, only the last serialized number will be saved.
  4. For fields that do not want to be serialized, you can add the TRANSIENT keyword before the field type (default value for deserialization).

2. Implement the Externalizable interface

A method must be overridden to implement the Externalizable interface

  • writeExternal(ObjectOutput out)
  • readExternal(ObjectInput in)

Here’s an example:

public class TextBean implements Externalizable {

    private Integer id;

    private String name;

    private Date date;
   
    // You can customize what needs to be serialized
    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeInt(id);
        out.writeObject(name);
        out.writeObject(date);
    }
    // You can customize what needs to be deserialized
    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        this.id = in.readInt();
        this.name = (String) in.readObject();
        this.date = (Date) in.readObject();
    }
    // Omit getter and setter methods and toString
}
Copy the code

Serialization:

public static void main(String[] args) {
    TextBean textBean = new TextBean();
    textBean.setDate(new Date());
    textBean.setId(1);
    textBean.setName("zll1");

    try (ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream("D:\\externalizable.txt"))) {
        outputStream.writeObject(textBean);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch(IOException e) { e.printStackTrace(); }}Copy the code

Deserialization:

public static void main(String[] args) {
    try (ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("D:\\externalizable.txt"))) {
        TextBean textBean = (TextBean) objectInputStream.readObject();
        System.out.println(textBean);
        TextBean{id=1, name='zll1', date=Fri Nov 27 16:49:17 CST 2020}
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch(ClassNotFoundException e) { e.printStackTrace(); }}Copy the code

Note:

  1. Serialized objects provide no-argument constructs
  2. If a field is not serialized, it is important not to deserialize the field that was serialized

3. The serialVersionUID

Here’s how serialization works: During serialization, the serialVersionUID of the current class is written to the byte sequence (and also to the serialized file). During deserialization, the serialVersionUID in the byte stream is compared to the serialVersionUID in the local object. InvalidCastException is reported if it is inconsistent.

SerialVersionUID: private static Final Long serialVersionUID= XXXL

  1. Explicit declaration: the default is 1L
  2. Explicit declaration: a 64-bit hash value computed based on package name, class name, inheritance relationship, non-private methods and attributes, parameters, return values, and many other factors
  3. Implicit declaration: If serialVersionUID is not explicitly declared, the Java serialization mechanism automatically generates a serialVersionUID based on the Class (preferably not, since the serialVersionUID generated automatically may change if the Class changes, Cause mismatch)

When adding attributes to a serialized class, it is best not to change the serialVersionUID to avoid deserialization failures

To create a Class in IDEA, press Alt + Enter on the Class name:

If the above information is not displayed, you can follow the following steps:

Four, the last

Converting objects into JSON strings and converting json strings into objects also belong to the category of serialization and deserialization. Compared with the serialization mechanism provided by JDK, each has its own advantages and disadvantages:

  • JDK serialization/deserialization: Native methods do not depend on other libraries, but cannot be used across platforms and are large in bytes
  • Json serialization/deserialization: JSON strings are readable, can be used across platforms without language restrictions, have good scalability, but require third-party class libraries, and have a large number of bytes

Want to know about the use of json can see here (mp.weixin.qq.com/s/S4R21FXSU…

Give it a thumbs up

If you think this article has helped you, please “read/retweet/like /star”, thanks

If you find something better or different, feel free to discuss it in the comments section


Welcome to pay attention to the public number: “actually white sheep” dry goods continue to update……