有没有一种方法可以在Java中禁用序列化对象的缓存?
我有这个情境:
- I have an object which is Serializable, I am serializing it, deserializing it, values are OK.
- On the same object, I am changing some value, I am serializing it, deserializing it, values are NOT OK, values are same as the first initially loaded.
好像序列化器在缓存值,是吗?
谢谢 (xiè xie)
抄了这个例子从“弗雷德里克”,并根据我的情况做了调整:
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;
}