在序列化和反序列化期间如何调用构造函数? [英] How are constructors called during serialization and deserialization?

查看:299
本文介绍了在序列化和反序列化期间如何调用构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在序列化和反序列化期间如何调用构造函数

How are the constructors called during serialization and deserialization


  1. 当有一个类实现可序列化时?

  2. 当有父/子关系并且只有子实现可序列化时?

  3. 当有父/子关系并且父和子实现可序列化时?


推荐答案

示例:

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;
    }
}

}

输出:

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.

这篇关于在序列化和反序列化期间如何调用构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆