gpt4 book ai didi

Java对象序列化和继承

转载 作者:IT老高 更新时间:2023-10-28 21:01:32 26 4
gpt4 key购买 nike

假设你有这两个类,Foo 和 Bar,其中 Bar 扩展 Foo 并实现 Serializable

class Foo {

public String name;

public Foo() {
this.name = "Default";
}

public Foo(String name) {
this.name = name;
}
}

class Bar extends Foo implements java.io.Serializable {

public int id;

public Bar(String name, int id) {
super(name);
this.id = id;
}
}

注意 Foo 没有实现 Serializable。那么当 bar 被序列化时会发生什么?

    public static void main(String[] args) throws Exception {

FileOutputStream fStream=new FileOutputStream("objects.dat");
ObjectOutputStream oStream=new ObjectOutputStream(fStream);
Bar bar=new Bar("myName",21);
oStream.writeObject(bar);

FileInputStream ifstream = new FileInputStream("objects.dat");
ObjectInputStream istream = new ObjectInputStream(ifstream);
Bar bar1 = (Bar) istream.readObject();
System.out.println(bar1.name + " " + bar1.id);

}

它打印“默认 21”。问题是,为什么在类没有序列化的时候会调用默认构造函数?

最佳答案

Serializable 只是给定类的“标记接口(interface)”。

但该类必须遵守某些规则:

http://docs.oracle.com/javase/1.5.0/docs/api/java/io/Serializable.html

To allow subtypes of non-serializable classes to be serialized, the subtype may assume responsibility for saving and restoring the state of the supertype's public, protected, and (if accessible) package fields. The subtype may assume this responsibility only if the class it extends has an accessible no-arg constructor to initialize the class's state. It is an error to declare a class Serializable if this is not the case.

回答@Sleiman Jneidi 在评论中提出的问题,在上面提到的oracle文档中,明确提到了

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class. A no-arg constructor must be accessible to the subclass that is serializable. The fields of serializable subclasses will be restored from the stream.

因此,调用的类 Foo 的默认无参数构造函数导致初始化。

关于Java对象序列化和继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8632148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com