我应该在java中覆盖readObject()writeObject()多少?

时间:2014-11-25 12:48:06

标签: java inheritance serialization

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

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(),itselsf但是我不知道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();
    }
}

1 个答案:

答案 0 :(得分:1)

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,因此序列化不会调用它们。

鉴于他们应该是私人的,使用@Override也是徒劳的。

由于您的代码可能有效,您可以从中得出结论,您根本不需要这样做。让序列化为你做。