有没有办法在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;
}
答案 0 :(得分:5)
答案 1 :(得分:0)
stepancheg是对的,你确定你没有重读第一个序列化对象吗?
以下示例有效。如果您可以创建类似的东西,请在此处发布。 import java.io。*;
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"));
obj = (ChangingObject)is.readObject();
System.out.println("obj.foo is "+obj.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"));
obj = (ChangingObject)is.readObject();
System.out.println("obj.foo is "+obj.foo);
} catch (Exception e) {
e.printStackTrace();
}
}
}
class ChangingObject implements Serializable {
public int foo;
}
编辑:如果我采用你改变的(好的,不是真的)例子,我仍然得到一个正确的输出(用2而不是第二个输出)。您建议重置应该没有区别,因为您重新打开文件并从读取和写入时开始。我认为你的问题出在其他地方(你在使用什么操作系统?,哪个文件系统?等等) 它应该工作,对不起。
答案 2 :(得分:-1)
Serializer没有缓存。
您应该展示如何重复案例的最小示例。