gpt4 book ai didi

java - 在java中,我应该重写多少readObject() writeObject()?

转载 作者:行者123 更新时间:2023-12-01 12:13:47 25 4
gpt4 key购买 nike

这似乎是一个奇怪的问题,但看看这个简单的代码:

public class Father implements Serializable{
private static final long serialVersionUID = 1L;
String familyName = "Josepnic";
String name = "Gabriel"
void writeObject (ObjectOutputStream out) throws IOException{
out.writeObject(familyName);
out.writeObject(name);
}
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
familyName = (String) in.readObject();
name = (String) in.readObject();
}
}
public class Child extends Father{
private static final long serialVersionUID = 1L;
String name = "Josep";
void writeObject (ObjectOutputStream out) throws IOException{
out.writeObject(name);
}
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
}
}

不知道Child是否也应该写他父亲的姓氏,还是会自动写? (我这么说是因为父亲有一个writeObject(),它本身有一个,但我不知道Java序列化的处理方式)。

也许一个好的建议是

public class Child extends Father{
private static final long serialVersionUID = 1L;
String name = "Josep";
@Override
void writeObject (ObjectOutputStream out) throws IOException{
super.writeObject(out);
out.writeObject(name);
}
@Override
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
super.readObject(in);
name = (String) in.readObject();
}
}

最佳答案

void writeObject (ObjectOutputStream out) throws IOException{
out.writeObject(familyName);
out.writeObject(name);
}
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
familyName = (String) in.readObject();
name = (String) in.readObject();
}

void writeObject (ObjectOutputStream out) throws IOException{
out.writeObject(name);
}
void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
name = (String) in.readObject();
}

您在发布的这些方法中放入什么内容根本不重要,因为它们都没有被调用。根据对象序列化规范的要求,它们不是私有(private),因此序列化不会调用它们。

鉴于它们应该是私有(private)的,使用 @Override 也是徒劳的。

由于您的代码可能有效,因此您可以仅凭这一点得出结论:您根本不需要这样做。让序列化为您做这件事。

关于java - 在java中,我应该重写多少readObject() writeObject()?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27127189/

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