Java对象序列化和继承 [英] Java object Serialization and inheritance

查看:162
本文介绍了Java对象序列化和继承的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say you have these two classes, Foo and Bar where Bar extends Foo and implements 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没有实现序列化。那么当序列化bar时会发生什么?

Notice that Foo doesn't implement Serializable. So what happens when bar is serialized?

    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。
问题是,为什么在未序列化类时调用默认构造函数?

it prints "Default 21". The question is, why the default constructor get called when the class is not serialized?

推荐答案

Serializable只是一个给定类的标记接口。

Serializable is just a "marker interface" for a given class.

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

But that class must adhere to certain rules:


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

允许非可序列化类的子类型为序列化后,
子类型可能负责保存和恢复超类型的public,protected和(如果可访问)包
字段的状态
。只有当扩展类
具有可访问的no-arg构造函数来初始化
类的状态时,子类型才可以承担此责任。声明类Serializable是错误的,如果
不是这样的话。

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文档中的
,明确提到

to answer @Sleiman Jneidi question asked in comment, in oracle documentation mentioned above, its clearly mentioned


在反序列化期间,非可序列化类的字段将是使用类的public或protected no-arg构造函数初始化。必须可以对可序列化的子类访问no-arg构造函数。可序列化子类的字段将从流中恢复。

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的默认no-arg构造函数导致初始化。

Thus, default no-arg constructor of class Foo called of, resulted in initialization.

这篇关于Java对象序列化和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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