如何在反序列化对象中添加新字段?

时间:2015-08-06 07:49:12

标签: java serialization

拥有一个班级Employee,其中包含员工NameEmployeeIdserialized字段。

现在我通过持久1000课程的deserialization来获得超过Employee个对象。

现在在address班级中添加了新字段Employee

如何将新字段address添加到已经deserialized个对象中?

注意:,不再执行任何deserialization

1 个答案:

答案 0 :(得分:0)

您可以创建一个从Employee扩展的包装类。

public class EmployeeWithAddr extends Employee {

    private String address;

    public EmployeeWithAddr(Employee employee) {
        //initialize from employee
    }

    public EmployeeWithAddr(Employee employee, String address) {
        //initialize from employee
        this.address = address;
    }

    public String getAddress() { 
        return address; 
    }

    public void setAddress(String address) {
        this.address = address;
    }

}

然后,你获取反序列化的对象,将它传递给包装器构造函数et voila,你就拥有它。

恕我直言,不需要黑魔法来改变运行时类并动态地在对象上添加新字段。这很好。