序列化扩展Java类的Scala类:值丢失了吗?

时间:2012-04-10 23:16:22

标签: java scala serialization

Foo.java

public class Foo{
  public int i = 0;
}

Bar.scala

class Bar() extends Foo with Serializable{
  i = 1 
}

通过Josh Seureth进行序列化https://stackoverflow.com/a/3442574/390708

import java.io._

  class Serialization{
    def write(x : AnyRef) {
    val output = new ObjectOutputStream(new FileOutputStream("test.obj"))
    output.writeObject(x)
    output.close()
  }

  def read[A] = {
    val input = new ObjectInputStream(new FileInputStream("test.obj"))
    val obj = input.readObject()
    input.close()
    obj.asInstanceOf[A]
  }
}

REPL会话,在序列化之前bar是1但在之后​​是0。

scala -cp .
Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.7.0_03).
Type in expressions to have them evaluated.
Type :help for more information.

scala> val bar = new Bar
bar: Bar = Bar@2d2ab673

scala> bar.i
res0: Int = 1

scala> :load Serialization.scala
Loading Serialization.scala...
import java.io._
defined class Serialization

scala> val serialization = new Serialization
serial: Serialization = Serialization@41a45f89

scala> serialization.write(bar)

scala> val bars = serialization.read[Bar]
bars: Bar = Bar@5a9948fd

scala> bars.i
res3: Int = 0

那么,为什么在这种情况下不是bars.i 1?

1 个答案:

答案 0 :(得分:8)

这是预期的,我相信与Scala无关。非序列化超类不是序列化的(因为它们不可序列化!)因此它们的值将由默认构造函数初始化。

如果您想以某种方式保存超类,则需要覆盖readObject和writeObject以手动保存状态。或者,使用更灵活的序列化解决方案来编写XML,JSON等,并使用反射。