How are constructors called during serialization and deserialization?

前端 未结 6 1415
感情败类
感情败类 2020-11-28 06:16

How are the constructors called during serialization and deserialization

  1. When there is one class implementing serializable?
  2. When there is parent/child
6条回答
  •  青春惊慌失措
    2020-11-28 06:53

    Example:

     public class ParentDeserializationTest {
    
        public static void main(String[] args){
            try {
                System.out.println("Creating...");
                Child c = new Child(1);
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ObjectOutputStream oos = new ObjectOutputStream(baos);
                c.field = 10;
                System.out.println("Serializing...");
                oos.writeObject(c);
                oos.flush();
                baos.flush();
                oos.close();
                baos.close();
                ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
                ObjectInputStream ois = new ObjectInputStream(bais);
                System.out.println("Deserializing...");
                Child c1 = (Child)ois.readObject();
                System.out.println("c1.i="+c1.getI());
                System.out.println("c1.field="+c1.getField());
            } catch (IOException ex){
                ex.printStackTrace();
            } catch (ClassNotFoundException ex){
                ex.printStackTrace();
            }
        }
    
        public static class Parent {
            protected int field;
            protected Parent(){
                field = 5;
                System.out.println("Parent::Constructor");
            }
            public int getField() {
                return field;
            }
        }
    
        public static class Child extends Parent implements Serializable{
            protected int i;
            public Child(int i){
                this.i = i;
                System.out.println("Child::Constructor");
            }
            public int getI() {
                return i;
            }
        }
    }
    

    Output:

    Creating...
    Parent::Constructor
    Child::Constructor
    Serializing...
    Deserializing...
    Parent::Constructor
    c1.i=1
    c1.field=5
    

    So if you deserialized your object, its constructors doesn't called, but default constructor of its parent will be called. And don't forget: all your serializable object should have a standard constructor without parameters.

提交回复
热议问题