假设我要为类定义自定义writeObjectreadObject以便进行序列化。该类具有最终属性(int),该属性在构造函数中初始化。在writeObject期间没有问题。但是在读回该对象时,我无法将值分配给属性,因为编译器提示无法覆盖final属性,并要求我从属性中删除final修饰符。有没有解决的办法?

下课可能会让您清楚地了解我要达到的目标。 this.age = in.readInt();中的readObject()给我编译错误。

public class Person {

private String name = null;
private final int age;

public Person(String name, int age)
{
    this.name = name;
    this.age = age;
}

public void writeObject(ObjectOutputStream out) throws IOException
{
    out.writeObject(name);
    out.writeInt(age);
}

public void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException
{
    this.name = (String) in.readObject();
    this.age = in.readInt();
}

}

最佳答案

默认的ObjectInputStream反序列化似乎使用sun.misc.Unsafe设置字段(java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(Object, Object[])),因此设置最终字段可能不是您想要执行的操作。正如Katona在评论中建议的那样,您可以执行以下操作:

public class Person implements Serializable {

    private String name = null;

    private final int age;

    private int ageFromRead;

    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }

    private void writeObject(ObjectOutputStream out) throws IOException {
        out.writeObject(name);
        out.writeInt(age);
    }

    private void readObject(ObjectInputStream in) throws IOException,
    ClassNotFoundException {
        this.name = (String) in.readObject();
        this.ageFromRead = in.readInt();
    }

    private Object readResolve() {
        return new Person(name, ageFromRead);
    }
}

关于java - 反序列化过程中回读自定义readObject中的最终值?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/18538484/

10-11 00:43