简体   繁体   中英

Serialization and Deserialization rules for member variable of Serializable Object

I have read Constructor Calls while serialization , Serialization Rules but can't able to find out all rule for member variable.

I have below question:

Student.java

class Person {
}
class Student extends Person implements Serialization {
   List<Book> books; 
   Student(){}
   Student(List<Book> books) {
      this.books = books;
   }
}

class Book implements Serialization {
  Book() {}
  String bookId;
  Book(String bookId) {
      this.bookId = bookId;
  }

}

Here Student is serializable and Book class is also serializable then what are rules for constructor calling serializable and deserializable.

  1. Is required default constructor in Book class? If Yes , Then Why required default constructor while deserialization.
  2. How constructor calls while serialization and deserialization?

See my answers below:

Is required default constructor in Book class?

-> Yes it is mandatory or else serialization will fail.

How constructor calls while serialization and deserialization?

-> Serialization uses reflection and a default constructor is mandatory to use reflection.

Actually, you should put a no-arg constructor in the class of Person which is the superclass of Student .

If don't, a java.io.InvalidClassException in runtime will be thrown when deserialization.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM