有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

下面是我的示例代码:

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

有人能解释为什么要耕种吗。z打印7? 栽培1的值。z在输出流关闭后递增。那么,这种改变是如何反映在去甲化过程中的呢


共 (2) 个答案

  1. # 1 楼答案

    z是一个静态字段,即它是一个类级字段,而不是一个特定于实例的字段

    静态变量属于一个类,而不属于任何单个实例。序列化的概念与对象的当前状态有关。只有与类的特定实例关联的数据才会被序列化,因此在序列化过程中会忽略静态成员字段

    所以在反序列化过程中,静态变量value的值将从类中加载

  2. # 2 楼答案

    静态变量未序列化,因此在反序列化期间,静态变量值将从类中加载。(将加载当前值。)

    这里是来自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.