Scala案例类序列化

时间:2016-11-15 10:51:48

标签: scala exception serialization case-class

我一直在尝试二进制序列化复合案例类对象,该对象不断抛出一个奇怪的异常。我真的不明白这个抛出以下异常的例子有什么问题。我曾经为循环引用得到了这个例外,这不是这里的情况。请给我一些提示?

java.lang.ClassCastException: cannot assign instance of scala.collection.immutable.List$SerializationProxy to field com.Table.rows of type scala.collection.immutable.List in instance of com.Table
java.lang.ClassCastException: cannot assign instance of scala.collection.immutable.List$SerializationProxy to field com.Table.rows of type scala.collection.immutable.List in instance of com.Table
    at java.io.ObjectStreamClass$FieldReflector.setObjFieldValues(ObjectStreamClass.java:2133)
    at java.io.ObjectStreamClass.setObjFieldValues(ObjectStreamClass.java:1305)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2024)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:1942)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1808)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
    at com.TestSeri$.serializeBinDeserialise(TestSeri.scala:37)
    at com.TestSeri$.main(TestSeri.scala:22)
    at com.TestSeri.main(TestSeri.scala)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)

这是代码

import java.io._    
import scalax.file.Path

case class Row(name: String)
case class Table(rows: List[Row])
case class Cont(docs: Map[String, Table])

case object TestSeri {
  def main(args: Array[String]) {
    val cc = Cont(docs = List(
      "1" -> Table(rows = List(Row("r1"), Row("r2"))),
      "2" -> Table(rows = List(Row("r301"), Row("r31"), Row("r32")))
    ).toMap)

    val tt = Table(rows = List(Row("r1"), Row("r2")))
    val ttdes = serializeBinDeserialize(tt)
    println(ttdes == tt)

    val ccdes = serializeBinDeserialize(cc)
    println(ccdes == cc)
  }

  def serializeBinDeserialize[T](payload: T): T = {
    val bos = new ByteArrayOutputStream()
    val out = new ObjectOutputStream(bos)
    out.writeObject(payload)

    val bis = new ByteArrayInputStream(bos.toByteArray)
    val in = new ObjectInputStream(bis)
    in.readObject().asInstanceOf[T]
  }
}

1 个答案:

答案 0 :(得分:0)

使用不可变的数组替换List,修复了问题。 在我原来的问题中,我有一个地图,我用TreeMap替换。

我认为可能与这里提到的通用不可变List和Map中的代理模式实现有关:

https://issues.scala-lang.org/browse/SI-9237

不能相信我浪费了整整一天的时间。