gpt4 book ai didi

java - 静态成员序列化

转载 作者:行者123 更新时间:2023-12-01 18:57:14 24 4
gpt4 key购买 nike

我读到“序列化不适用于静态元素” - 但下面的一个简单示例告诉我事实并非如此。

class superparent implements Serializable {
int data = 0;

public superparent(int data) {
this.data = data;
}

public int getdata() {
return data;
}
}

public class statichost implements Serializable {
int member = 0;
public static superparent s = new superparent(20);

public statichost(int data) {
this.member = data;
}

public static void main(String[] args) {
statichost c = new statichost(6);
try {
FileOutputStream fs = new FileOutputStream("testSer.ser");
ObjectOutputStream os = new ObjectOutputStream(fs);
os.writeObject(c);
os.close();
} catch (Exception e) {
e.printStackTrace();
}

try {
FileInputStream fis = new FileInputStream("testSer.ser");
ObjectInputStream ois = new ObjectInputStream(fis);
c = (statichost) ois.readObject();
ois.close();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("after: contained data is " + c.s.getdata());
}
}

当我按照上面的语句期望输出 0 时,输出打印 20。我错过了什么吗?

最佳答案

这是因为您的int data=0;不是您的类superparent的静态成员。

此外,如果您忘记了此建议,我还想指出类名应以大写字母开头

关于java - 静态成员序列化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13559419/

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