gpt4 book ai didi

扩展类的 Java 序列化

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

在 java 序列化类 Mp3player extends ElectronicDevice implements Serializable 中,父类(super class) electronicdevice 未实现可序列化。这里的父类(super class)也被序列化了。我的理解是父类(super class)也由于扩展而被序列化。让我知道我的理解是否正确。

 import java.io.*;
class ElectronicDevice {
ElectronicDevice()
{
System.out.print("ed ");
}
}
class Mp3player extends ElectronicDevice implements Serializable {
Mp3player()
{
System.out.print("mp ");
}
}
class MiniPlayer extends Mp3player {
MiniPlayer()
{
System.out.print("mini ");
}
public static void main(String[] args) {
MiniPlayer m = new MiniPlayer();
try {
FileOutputStream fos = new FileOutputStream("dev.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(m); os.close();

FileInputStream fis = new FileInputStream("dev.txt");
ObjectInputStream is = new ObjectInputStream(fis);
MiniPlayer m2 = (MiniPlayer) is.readObject();
is.close();
System.out.println();
} catch (Exception x) {
System.out.print("x ");
}
}
}

最佳答案

没有。在序列化过程中只有Seri​​alizable对象的字段被写出和恢复。

根据 javadocs

During deserialization, the fields of non-serializable classes will be initialized using the public or protected no-arg constructor of the class.

Where as the fields of serializable subclasses will be restored from the stream.

请看这个例子
这里ElectronicDevice不是Serializable,而Mp3playerSerializable。在序列化过程中观察尊重类行为的字段.

import java.io.*;
class ElectronicDevice {
public int i = 0;
protected ElectronicDevice()
{
System.out.println("ed ");
}
}
class Mp3player extends ElectronicDevice implements Serializable {
int j =0;
Mp3player()
{
System.out.println("mp ");
}
}
class MiniPlayer extends Mp3player {
MiniPlayer()
{
System.out.println("mini ");
}
public static void main(String[] args) {
MiniPlayer m = new MiniPlayer();
m.i = 30;
m.j = 40;
try {
System.out.println("i value before serialization: "+m.i);//prints 30
System.out.println("i value before serialization: "+m.j);//prints 40
FileOutputStream fos = new FileOutputStream("dev.txt");
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(m); os.close();

FileInputStream fis = new FileInputStream("dev.txt");
ObjectInputStream is = new ObjectInputStream(fis);
MiniPlayer m2 = (MiniPlayer) is.readObject();
is.close();
System.out.println("i value after serialization: "+m2.i);//prints o
System.out.println("j value after serialization: "+m2.j);//prints 40
System.out.println();
} catch (Exception x) {
x.printStackTrace();
System.out.print("x ");
}
}
}

关于扩展类的 Java 序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18417737/

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