小编Igo*_*orS的帖子

禁用序列化缓存

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

我有这种情况:

  1. 我有一个Serializable的对象,我正在序列化它,反序列化它,值是可以的.
  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 …
Run Code Online (Sandbox Code Playgroud)

java serialization

1
推荐指数
1
解决办法
1744
查看次数

标签 统计

java ×1

serialization ×1