下面是我的示例代码:
public class Hybrid {
public static void main(String[] args) {
Cultivate cultivate1 = new Cultivate();
try{
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("myfile"));
os.writeObject(cultivate1);
os.close();
System.out.println("line 1 : "+ ++cultivate1.z+" ");
ObjectInputStream is = new ObjectInputStream(new FileInputStream("myfile"));
Cultivate cultivate2 = (Cultivate)is.readObject();
is.close();
System.out.println("line 2 : "+cultivate1.y+" "+cultivate2.z);
} catch(Exception x){
System.out.println("exc");
}
}
}
class Cultivate implements Serializable{
transient int y=3;
static int z = 6;
}
这是输出:
line 1 : 7
line 2 : 3 7
有人可以解释一下为什么sculpt2.z 打印 7 吗? 输出流关闭后,cult1.z 的值会递增。那么这种修改如何反射(reflect)在反序列化中呢?
最佳答案
静态变量没有序列化,因此在反序列化期间静态变量值将从类中加载。(将加载当前值。)
这里是来自 ObjectOutputStream 的 JavaDoc:
The default serialization mechanism for an object writes the class of the object, the class signature, and the values of all non-transient and non-static fields. References to other objects (except in transient or static fields) cause those objects to be written also. Multiple references to a single object are encoded using a reference sharing mechanism so that graphs of objects can be restored to the same shape as when the original was written.
关于Java序列化-将对象写入文件后修改对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39143031/