gpt4 book ai didi

java - 继承序列化 (Java)

转载 作者:塔克拉玛干 更新时间:2023-11-02 08:01:47 25 4
gpt4 key购买 nike

我正在学习序列化和继承,但我不明白谁在反序列化过程中调用了无参数构造函数。父类(super class) A 不实现 Serializable,子类 B 扩展 A 实现 Serializable。

父类(super class) A

public class A {

int i;

public A(int i)
{
this.i = i;
}

public A()
{
i = 50;
System.out.println("A's class constructor called");
}
}

B 类

import java.io.Serializable;

public class B extends A implements Serializable {

int j;

// parameterized constructor
public B(int i,int j)
{
super(i);
this.j = j;
}
}

驱动类

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Test {

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

B b1 = new B(10,20);

System.out.println("i = " + b1.i);
System.out.println("j = " + b1.j);

// Serializing B's(subclass) object

//Saving of object in a file
FileOutputStream fos = new FileOutputStream("abc.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);

// Method for serialization of B's class object
oos.writeObject(b1);

// closing streams
oos.close();
fos.close();

System.out.println("Object has been serialized");

// De-Serializing B's(subclass) object

// Reading the object from a file
FileInputStream fis = new FileInputStream("abc.ser");
ObjectInputStream ois = new ObjectInputStream(fis);

// Method for de-serialization of B's class object
B b2 = (B)ois.readObject(); // The A() constructor is called here

// closing streams
ois.close();
fis.close();

System.out.println("Object has been deserialized");

System.out.println("i = " + b2.i);
System.out.println("j = " + b2.j);
}
}

如果我删除 A() 构造函数,我将得到 InvalidClassException。我看到在创建 b2 对象时调用了 A() 但我不明白为什么在此语句中调用此 A() 以及调用它的人。

当创建 b1 对象时,将调用 B(int i, int j) 构造函数和 A(int i) 构造函数。这很容易理解。但是我不明白为什么在创建 b2 对象时调用 A() 构造函数。

最佳答案

来自 Serializable JavaDocs :

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. The error will be detected at runtime.

现在回答你的问题:

If I delete the A() constructor I get the InvalidClassException. I see that A() is called when the b2 object is created but I don't understand why this A() is called at this statement and who called it.

A() 构造函数由序列化机制通过反射调用。具体来自 ObjectInputStream 通过 ObjectStreamClass

关于java - 继承序列化 (Java),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49842861/

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