Java序列化-将对象写入文件后修改对象

标签 java serialization deserialization

下面是我的示例代码:

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/

相关文章:

java - 为什么ObjectMapper将Date类型改为Long

java - 如何在java中生成20到100之间5个随机数的列表

java - 有序流的减少是否按顺序减少?

c# - C# 中用于嵌套节点的 XML 序列化

java - RMI 上的大字节数组

java - 序列化 Path2D.Double 的子类时为 "no valid constructor"

java.lang.OutOfMemoryError : PermGen space in play framework

java - 无法初始化 org.eclipse.wst.server.ui.internal.provisional.UIDecoratorManager 尝试启动本地服务器时出错

c# - 在 C# 中反序列化 JSON 数组(或列表)

java - 使用 Jackson 序列化和反序列化针对 JAVA 类的 JSON