避免Java反序列化中的重复对象 [英] Avoiding duplicate objects in Java deserialization

查看:37
本文介绍了避免Java反序列化中的重复对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个列表(list1 和 list2)包含对某些对象的引用,其中某些列表条目可能指向同一个对象.然后,出于各种原因,我将这些列表序列化为两个单独的文件.最后,当我反序列化列表时,我想确保我不会重新创建比需要更多的对象.换句话说,List1 的某些条目仍然可能指向与 List2 中的某些条目相同的对象.

I have two lists (list1 and list2) containing references to some objects, where some of the list entries may point to the same object. Then, for various reasons, I am serializing these lists to two separate files. Finally, when I deserialize the lists, I would like to ensure that I am not re-creating more objects than needed. In other words, it should still be possible for some entry of List1 to point to the same object as some entry in List2.

MyObject obj = new MyObject();
List<MyObject> list1 = new ArrayList<MyObject>();
List<MyObject> list2 = new ArrayList<MyObject>();
list1.add(obj);
list2.add(obj);

// serialize to file1.ser
ObjectOutputStream oos = new ObjectOutputStream(...);
oos.writeObject(list1);
oos.close();

// serialize to file2.ser
oos = new ObjectOutputStream(...);
oos.writeObject(list2);
oos.close();

我认为 spec 说反序列化严格导致新对象的创建,但我不确定.如果是这样,一些可能的解决方案可能涉及:

I think that sections 3.4 and A.2 of the spec say that deserialization strictly results in the creation of new objects, but I'm not sure. If so, some possible solutions might involve:

  1. 实现 equals() 和 hashCode() 并手动检查引用.
  2. 创建一个容器类"来保存所有内容,然后序列化容器类.

是否有一种简单的方法可以确保反序列化时对象不会重复?

Is there an easy way to ensure that objects are not duplicated upon deserialization?

谢谢.

推荐答案

在反序列化第二个列表后,您可以迭代它的元素并通过对第一个列表的引用替换重复项.

After deserialization of the second list you could iterate over it's the elements and replace duplicates by a reference to the first list.

根据3.7的readResolve方法 readResolve() 方法在对象完全构造之前不会在对象上调用.

According to 3.7 The readResolve Method the readResolve() method is not invoked on the object until the object is fully constructed.

这篇关于避免Java反序列化中的重复对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆