Guava SetMultimap 不可序列化(由于不可序列化 WrappedSet)
我经常使用java序列化,这对于存储完整的对象层次结构非常有用。
当尝试序列化 SetMultimap 时,我收到一个异常,说 AbstractMultimap.WrappedSet 不可序列化。
番石榴用户如何解决这个问题?
提前致谢,
I'm often using java serialization, which is very usefull to store a complete object hierarchy.
When trying to serialize a SetMultimap, I got an exception saying that that AbstractMultimap.WrappedSet is not serializable.
How do guava users workaround with this problem?
Thanks in advance,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
multimap 元素的视图(例如从
get
方法返回的集合、asMap
视图等)故意不可序列化。但是,SetMultimap
实现因此而无法序列化是不正确的。 Guava 提供的所有SetMultimap
实现实际上都是可序列化的……只是它们的部分视图集合不是可序列化的。如果您需要序列化这些集合之一,则应将其显式复制到普通集合:
The views of elements of a multimap (such as the collections returned from
get
methods, theasMap
view, etc.) are intentionally not serializable. However, it isn't true that aSetMultimap
implementation would not be serializable because of that. All implementations ofSetMultimap
that Guava provides are in fact serializable... it's just the partial view collections for them that are not.If you need to serialize one of these collections, you should explicitly copy it to a normal collection:
Edit 所以查看
AbstractMultimap
的源码,返回的Map
是一个AsMap
或者SortedAsMap
,两者都不可序列化。我建议创建一个新的HashMap
并使用putAll
方法传入Multimap.asMap()
结果。HashMap
是可序列化的。Edit So looking at the source of
AbstractMultimap
, theMap
that is returned is anAsMap
orSortedAsMap
, neither of which are serializable. I would suggest creating a newHashMap
and use theputAll
method passing in theMultimap.asMap()
result.HashMap
is serializable.