Java study notes (thirteen)--serialization, deserialization and no-argument constructor

concept

  1. Serialization: Save objects to disk, or allow objects to be transferred directly over the network. The object serialization mechanism allows Java objects in memory to be converted into platform-independent binaries, which can be persisted on disk or on the network. in transmission.
  2. Deserialization: Once the program obtains the serialized object, the binary stream can be restored to the original

How to implement serialization

    1.Serializable

The object to be serialized, implementing this interface, without overriding any methods

    2.Externalizable

The object to be serialized implements this interface and needs to implement the writeExternal and readExternal methods

Serialization of simple objects

 1. Single object serialization

  • Create a Person class

public class Person implements Serializable{
    private String id;

    public Person(String id) {
        System.out.println("youcacn");
        this.id = id;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                '}';
    }

    public String getId() {
        return id;
    }

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

   Note: 1.Person class implements the Serializable interface

           2. The entity class does not provide a parameterless constructor

  •  Write a test class to test serialization and deserialization      

try {
            //Serialization
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("2.txt"));
            Person person = new Person("111");
            objectOutputStream.writeObject(person);
            // deserialize
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("2.txt"));
            Person person1 = (Person) objectInputStream.readObject();
            System.out.println(person1.toString());
        } catch (Exception e) {
            e.printStackTrace ();
        }

  •    Results of the


  •   The Person class removes the implementation of the serialization interface (that is, changes public class Person implements Serializable to public class Person), and re-executes


    Conclusion: The serialization interface must be implemented when the object of a simple type (no inheritance relationship) is serialized, and there is a key with or without a parameterless constructor.

2. Object serialization with inheritance relationship but no reference relationship

  • Create the Student class and inherit the Person class
public class Student extends Person implements Serializable{
    private int no;

    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                '}';
    }

    public Student(String id ,int no) {
        super(id);
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

}
  • The Person class object neither implements the serialization interface nor provides a parameterless constructor
public class Person{
    private String id;

//    public Person() {
//    }

    public Person(String id) {
        System.out.println("youcacn");
        this.id = id;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                '}';
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
  • Perform serialization and deserialization

  • Another Person object implements the serialization interface, executes it again, and the result is successful
public class Person implements Serializable{
    private String id;

//    public Person() {
//    }

    public Person(String id) {
        System.out.println("youcacn");
        this.id = id;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                '}';
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
  • Does not implement the serialization interface, provides a no-argument constructor, and the execution result is successful
public class Person {
    private String id;

    public Person() {
    }

    public Person(String id) {
        System.out.println("youcacn");
        this.id = id;
    }

    @Override
    public String toString() {
        return "Person{" +
                "id='" + id + '\'' +
                '}';
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }
}
  Conclusion: When there is an inheritance relationship, if you want to serialize the subclass object and serialize the parent class object together, the responsible type must implement the serialization interface or provide a parameterless constructor

Serialization of object references

  •     The Student class inherits the Person class and has an object reference relationship
public class Student extends Person implements Serializable {
    private int no;
    private Person person;

    public Person getPerson() {
        return person;
    }

    public void setPerson(Person person) {
        this.person = person;
    }
        
    @Override
    public String toString() {
        return "Student{" +
                "no=" + no +
                '}';
    }

    public Student(String id, int no) {
        super(id);
        this.no = no;
    }

    public int getNo() {
        return no;
    }

    public void setNo(int no) {
        this.no = no;
    }

}
  • A demo serializes and deserializes Student instances
try {
            //Serialization
            ObjectOutputStream objectOutputStream = new ObjectOutputStream(new FileOutputStream("2.txt"));
            Person person = new Person("111");
            Student stuB = new Student("B", 163);
            stuB.setPerson (person);
            objectOutputStream.writeObject(stuB);
            // deserialize
            ObjectInputStream objectInputStream = new ObjectInputStream(new FileInputStream("2.txt"));
            Student student  = (Student) objectInputStream.readObject();
            System.out.println(student.getPerson());
        } catch (Exception e) {
            e.printStackTrace ();
        }
  • The Person class does not implement the serialization interface, nor does it provide a parameterless constructor. The execution results are as follows:

  • The Person class does not implement the serialization interface and provides a parameterless constructor. The execution results are as follows:


  • The Person class implements the serialization interface, but does not provide a parameterless constructor. The execution results are as follows:


in conclusion

  1. Single object, no inheritance relationship: If you want to achieve serialization and deserialization, you must implement the serialization interface, otherwise an exception will be reported: NotSerializableException
  2. There is an inheritance relationship between objects, but no reference relationship. If you want to achieve serialization and deserialization, the parent class must implement the serialization interface or provide a no-argument constructor, otherwise an invalidClassException will be reported.
  3. There is an inheritance relationship between objects and a reference relationship. If you want to achieve serialization and deserialization, the parent class must implement the serialization interface

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325935881&siteId=291194637