在 Scala 中序列化优先队列 [英] Serializing a priority queue in scala

查看:38
本文介绍了在 Scala 中序列化优先队列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在 Scala (2.10) 中序列化一个可变的 PriorityQueue 并且在将对象写入 ObjectOutputStream 时收到一个 NotSerializableException.我做了一个简单的测试用例:

I am trying to serialize a mutable PriorityQueue in scala (2.10) and am getting a NotSerializableException when writing the object to an ObjectOutputStream. I made a simple test case:

import java.io.{ByteArrayOutputStream, ObjectOutputStream}
import scala.collection.mutable

object Test extends App {
  val pq = new mutable.PriorityQueue[Int]()
  val oos = new ObjectOutputStream(new ByteArrayOutputStream())
  oos.writeObject(pq)
}

例外是

Exception in thread "main" java.io.NotSerializableException:scala.collection.mutable.PriorityQueue$ResizableArrayAccess
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1180)
at java.io.ObjectOutputStream.defaultWriteFields(ObjectOutputStream.java:1528)
at java.io.ObjectOutputStream.writeSerialData(ObjectOutputStream.java:1493)
at java.io.ObjectOutputStream.writeOrdinaryObject(ObjectOutputStream.java:1416)
at java.io.ObjectOutputStream.writeObject0(ObjectOutputStream.java:1174)
at java.io.ObjectOutputStream.writeObject(ObjectOutputStream.java:346)
at Test$.main(Test.scala:7)

似乎 PriorityQueue 应该是可序列化的,我能做些什么来解决这个问题吗?

It seems like a PriorityQueue should be serializable, is there something I can do to get around this?

推荐答案

这应该被报告为一个错误 - 修复是简单地使嵌套的 ResizableArrayAccess 类继承 Serializable.

This should be reported as a bug - the fix is to simply make the nested ResizableArrayAccess class inherit Serializable.

从技术上讲,也许您可​​以使用反射删除优先级队列类中 resarr 字段上的 privatefinal 修饰符,然后设置序列化前将其设为 null.

Technically, maybe you could use reflection to remove the private and final modifiers on the resarr field in the priority queue class, then set it to null before serialization.

否则,在序列化之前将优先级队列转换为数组,反序列化时反之亦然,将避免此异常.您可以在 PriorityQueue 周围滚动您自己的包装器以实现自定义序列化/反序列化.

Otherwise, converting the priority queue to a, say, array before serialization and vice versa on deserialization would avoid this exception. You could roll in your own wrapper around the PriorityQueue to implement custom serialization/deserialization.

注意:此问题已在 Scala 2.11.0-M7 (SI-7568)

Note: This issue has been resolved in Scala 2.11.0-M7 (SI-7568)

这篇关于在 Scala 中序列化优先队列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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