Home  >  Article  >  类库下载  >  Java serialization and deserialization

Java serialization and deserialization

高洛峰
高洛峰Original
2016-10-29 10:56:571541browse

1. What is serialization? Why serialize?

  Java serialization refers to the process of converting objects into byte sequences, while deserialization is the process of converting only byte sequences into target objects.

  We all know that when accessing a browser, the text, pictures, audio, video, etc. we see are transmitted through binary sequences. So if we need to transmit Java objects, is it also possible? Should the object be serialized first? The answer is yes, we need to serialize the Java object first, and then transmit it through the network and IO. When it reaches the destination, deserialize it to get the object we want, and finally complete the communication.

2. How to implement serialization

 2.1. Use the key classes ObjectOutputStream and ObjectInputStream in JDK

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

  In the ObjectInputStream class: By using the readObject() method, the binary stream is read from the input stream and converted into an object.

  2.2. The target object needs to implement the Serializable interface first

  

We create a Student class:

public class Student implements Serializable {
    private static final long serialVersionUID = 3404072173323892464L;
    private String name;
    private transient String id;
    private String age;

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Student(String name, String id) {
        System.out.println("args Constructor");
        this.name = name;
        this.id = id;
    }

    public Student() {
        System.out.println("none-arg Constructor");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

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

}

                                   over over from the code. The Student class implements the Serializable interface and generates a version number:

private static final long serialVersionUID = 3404072173323892464L;

   First:

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 serialization version number is used to distinguish the version of the class we write and to determine whether the version of the class is consistent during deserialization. If it is inconsistent, a version inconsistency exception will occur.

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

  2.3. Serialize or deserialize objects

   2.3.1 The first writing method:

public static  void main(String[] args){
        File file = new File("D:/test.txt");
        Student student = new Student("孙悟空","12");
        try {
            ObjectOutputStream outputStream = new ObjectOutputStream(new FileOutputStream(file));
            outputStream.writeObject(student);
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream(file));
            Student s = (Student) objectInputStream.readObject();
            System.out.println(s.toString());
            System.out.println(s.equals(student));
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

   Create the object Student, and then output the object to the file through the writeObject() method in the ObjectOutputStream class.

     Then deserialize through the readObject() method in the ObjectinputStream class to obtain the object.

    2.3.2 The second writing method:

Implement the writeObject() and readObject() methods in the Student class:

private void writeObject(ObjectOutputStream objectOutputStream) throws IOException {
        objectOutputStream.defaultWriteObject();
        objectOutputStream.writeUTF(id);

    }

    private void readObject(ObjectInputStream objectInputStream) throws IOException, ClassNotFoundException {
        objectInputStream.defaultReadObject();
        id = objectInputStream.readUTF();
    }

   Through this method of serialization, we can customize the serialization we want Variables, the input stream and output stream are passed into the line instance, and then serialized and deserialized.

 

    2.3.3 The third writing method:

Student implements the Externalnalizable interface but does not implement the Serializable interface

The Externaliable interface is a subclass of Serializable and has the same functions as the Serializable interface:

public class Student implements Externalizable {
    private static final long serialVersionUID = 3404072173323892464L;
    private String name;
    private transient String id;
    private String age;

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

    public String getAge() {
        return age;
    }

    public void setAge(String age) {
        this.age = age;
    }

    public Student(String name, String id) {
        System.out.println("args Constructor");
        this.name = name;
        this.id = id;
    }

    public Student() {
        System.out.println("none-arg Constructor");
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getId() {
        return id;
    }

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


    @Override
    public void writeExternal(ObjectOutput out) throws IOException {
        out.writeObject(name);
        out.writeObject(id);
    }

    @Override
    public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException {
        name = (String) in.readObject();
        id = (String) in .readObject();
    }

}

  Through the previous Comparing the second writing method, we can find that their implementation principles are very similar, but implementing the Externalnalizable interface does not support the first serialization method. It can only implement writeExternal() and readExternal() in the interface. Method implements serialization of objects.

3. Questions about serialization in interviews:

1. What is serialization and how to implement serialization

The serialization of objects in Java is to convert the object into a binary sequence, and deserialization is Convert a binary sequence into an object

   There are many ways to implement serialization in Java

  1. First, you need to use the two IO classes ObjectInputStream and ObjectOutputStream of the tool class

                                     duct ObjectInputStream Specific serialization method :

                                               ulous in in in ining in in on in the writeObject() and readObject() methods in the ObjectOutputStream and ObjectInputStream classes

     2.2 By implementing the writeObject() and readObject() methods in the serialized object, pass in the ObjectOutputStream and ObjectInputStream objects to complete the serialization

    3. Implement the Externalizable interface:

      Object serialization can only be achieved by implementing the writeExternal() and readExternal() methods in the interface


   2. Transient keyword? How to serialize variables modified with transient modifier?
    The function of transient is to shield variables that we do not want to serialize. The object ignores the variable during the serialization and deserialization process.
    We can implement the writeObject and readObject methods in the above serialization method, and call the writeUTF() and readUTF() methods of the output stream or input stream in the method.
   Or by implementing the Externalizable interface, implement the writeExternal() and readExternal() methods, and then customize the sequence object.

      3. How to ensure that the objects after serialization and deserialization are consistent? (Please correct me if you have any objections)
    After consulting some information on this issue, I found that there is no guarantee that the objects after serialization and deserialization are consistent, because during the deserialization process, we first create a Object,
     
     Therefore, we can only ensure that their data and versions are consistent, but we cannot guarantee that the objects are consistent.


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn