gpt4 book ai didi

java - 禁用序列化缓存

转载 作者:行者123 更新时间:2023-11-29 04:04:45 25 4
gpt4 key购买 nike

有没有办法在 Java 中禁用序列化对象的缓存?

我有这种情况:

  1. 我有一个可序列化的对象,我正在对其进行序列化、反序列化,值都正常。
  2. 在同一个对象上,我正在更改一些值,我正在对其进行序列化、反序列化,值不正确,值与最初加载的第一个值相同。

似乎序列化程序正在缓存这些值,或者没有?

谢谢

从“fredrik”复制了这个例子并采用到我的案例中:

public class SerialDeserial {
public static void main(String[] args) {
try {
ChangingObject obj = new ChangingObject();
obj.foo=1;
// Write it
ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream("test.foo"));
os.writeObject(obj);
os.flush();os.close();

// Read the object
ObjectInputStream is = new ObjectInputStream(new FileInputStream("test.foo"));
ChangingObject objDummy = (ChangingObject)is.readObject();
System.out.println("objDummy.foo is "+objDummy.foo);

// Change it
obj.foo=2;
// Write it
os = new ObjectOutputStream(new FileOutputStream("test.foo"));
os.writeObject(obj);
os.flush();os.close();

// Read the object
is = new ObjectInputStream(new FileInputStream("test.foo"));
objDummy = (ChangingObject)is.readObject();
System.out.println("objDummy.foo is "+objDummy.foo); // this returns "1" insted of "2"


} catch (Exception e) {
e.printStackTrace();
}
}
}

class ChangingObject implements Serializable {
public int foo;
}

最佳答案

ObjectOutputStream.reset .

你也可以用writeUnshared来写对象,但这很浅,所以引用的对象仍将被共享。

当然,不可变对象(immutable对象)一如既往地胜出。

关于java - 禁用序列化缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/673096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com