有没有办法在 Java 中禁用序列化对象的缓存?
我有这种情况:
- 我有一个可序列化的对象,我正在对其进行序列化、反序列化,值都正常。
- 在同一个对象上,我正在更改一些值,我正在对其进行序列化、反序列化,值不正确,值与最初加载的第一个值相同。
似乎序列化程序正在缓存这些值,或者没有?
谢谢
从“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;
}
最佳答案
关于java - 禁用序列化缓存,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/673096/