当只有子类实现可序列化时,序列化如何工作


问题内容

子类具有已实现的Serializable接口。

import java.io.*;

public class NewClass1{

    private int i;
    NewClass1(){
    i=10;
    }
    int getVal() {
        return i;
    }
    void setVal(int i) {
        this.i=i;
    }
}

class MyClass extends NewClass1 implements Serializable{

    private String s;
    private NewClass1 n;

    MyClass(String s) {
        this.s = s;
        setVal(20);
    }

    public String toString() {
        return s + " " + getVal();
    }

    public static void main(String args[]) {
        MyClass m = new MyClass("Serial");
        try {
            ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("serial.txt"));
            oos.writeObject(m); //writing current state
            oos.flush();
            oos.close();
            System.out.print(m); // display current state object value
        } catch (IOException e) {
            System.out.print(e);
        }
        try {
            ObjectInputStream ois = new ObjectInputStream(new FileInputStream("serial.txt"));
            MyClass o = (MyClass) ois.readObject(); // reading saved object
            ois.close();
            System.out.print(o); // display saved object state
        } catch (Exception e) {
            System.out.print(e);
        }
    }
}

我在这里注意到的一件事是,父类未序列化。然后,为什么它没有抛出却NotSerializableException确实显示了以下内容

输出量

Serial 20
Serial 10

同样,输出不同于SerializationDe- serialization。我只知道,这是因为父类尚未实现Serializable。但是,如果有人向我解释,在对象序列化和反序列化期间会发生什么。它如何改变价值?我不知道,我在程序中使用了注释。因此,如果我在任何时候错了,请告诉我。


问题答案:

根据可序列化的javadoc

反序列化期间,将使用该类的公共或受保护的无参数构造函数来初始化不可序列化类的字段。无参数构造函数必须对可序列化的子类可访问。可序列化子类的字段将从流中恢复。

同样,仅当要序列化的类不可序列化时,才会引发序列化异常。拥有不可序列化的父母是可以的(只要他们有一个无参数的构造函数)。对象本身不是可序列化的,并且一切都会对其进行扩展。上面的引用还说明了为什么您为value字段获得不同的值-
设置了父类的no-arg构造函数,该构造函数将value字段设置为10-该字段属于(不可序列化的)父类,因此其值不是写入/读取流。