Java序列化能否将对象反序列化为父类的实例

时间:2018-10-30 11:07:31

标签: java serialization

我有一个实现Serializable的基类。

class Base implements Serializable { 
    ... //some fields
}

我还有另一个扩展基类的类。

class Another extends Base { 
    ... //some fields
}

我有一个Another的序列化实例。我可以将其反序列化为Base的实例吗?

1 个答案:

答案 0 :(得分:0)

是的,通常您可以这样做。

忽略流初始化,关闭,异常等的最简单示例。

class Base implements Serializable { 
    String a;
    Base(String a) { this.a = a; }
}
class Access extends Base { 
    String b;
    Base(String a, String b) { super(a); this.b = b; }
}
class Test {
    public static void main(String[] args) {
        Access access = new Access("string1", "string2");
        // Serialization  
        ObjectOutputStream out = new ObjectOutputStream(...);
        out.writeObject(access);
        // Deserialization 
        ObjectInputStream in = new ObjectInputStream(...);
        Base base = (Base) in.readObject();
        System.out.println("Base.a = " + base.a); // ok, prints "string1"
        // System.out.println("Access.b = " + base.b); // -> compilation error -- this is not an Access object; "string2" has not been deserialized.
    }
}

但是,没有什么理由这样做。您总是可以反序列化为Access来获取所有数据,然后根据需要强制转换为Base