我可以更改成员变量类型的可序列化类吗?

时间:2015-06-23 13:27:55

标签: java serialization

假设一个类实现了serializable,我序列化了该类的对象。之后我改变了内部实现,以便将变量的数据类型从int更改为String。是否可以在使用readresolve进行反序列化时从序列化对象获取值?

Class A implements Serializable{
  private int first;
  private int second;

}
序列化后

Class A implements Serializable{

 private int first;
 private String second;

}

2 个答案:

答案 0 :(得分:0)

您需要实现自定义的readObject()方法。更多信息here

serialVersionUID在类的两个版本中也需要相同。如果您还没有声明serialVersionUID,那么jvm将根据类的形状计算它。为此,您需要在新版本的类中显式声明旧的serialVersionUID。更多信息here

答案 1 :(得分:0)

钻孔。我们试试这个(未编译)......

import java.io.*;

class A implements Serializable {
    private static final long serialVersionUID = 0x...L;
    private static final ObjectStreamField[] serialPersistentFields = {
        new ObjectStreamField("first", int.class),
        new ObjectStreamField("second", int.class),
        new ObjectStreamField("secondString", String.class),
    };
    private int first;
    private String second;

    private void writeObject(ObjectOutputStream out) throws IOException {
         ObjectOutputStream.PutField fields = out.putFields();
         fields.put("first", first);
         int secondInt;
         try {
             secondInt = Integer.parseInt(second);
         } catch (NumberFormatException exc) {
             secondInt = -1;
         }
         fields.put("second", secondInt);
         fields.put("secondString", second);
     }
     private void readObject(
         ObjectInputStream in
     ) throws IOException, ClassNotFoundException {
         ObjectInputStream.GetField fields = out.readFields();
         fields = fields.get("first", 0);
         int secondInt = fields.get("second", 0);
         second = (String)field.get("secondString", Integer.toString(secondInt));
     }
}

如果其中一个字段为final,那么您需要readResolve奇怪或更糟。

(差不多将最后secondInt留给那里second。嘘嘘到String.valueOf。)