简体   繁体   English

Scala嵌套对象序列化

[英]Scala Nested Object Serialization

Hi I have a case class A which contains variables pointing to another class B (with companion object, which has variables pointing to yet another class C which also has companion object). 嗨,我有一个案例类A,其中包含指向另一个类B的变量(带有随播对象,该对象具有指向另一个也具有同伴对象的类C的变量)。 class B and C are from other libraries. B和C类来自其他库。 What is the easier way that I could serialize my case class A? 序列化案例类A的简便方法是什么?

case class A() {
  val b = B
}

//B & C are defined in a library that I have no control of
object B {
  val c = C
} 

class B{
  ...
}

object C{
  ...
}  

class C{
  ...
}

If these classes are already Serializable , you don't need to do anything special, so the rest of the answer assumes they aren't. 如果这些类已经是Serializable ,那么您不需要做任何特殊的事情,因此其余答案假定它们不是。

If these fields can be reconstructed from others, mark them as @transient and implement readObject (as described in http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html ) to restore them. 如果可以从其他字段重构这些字段,请将其标记为@transient并实现readObject (如http://docs.oracle.com/javase/8/docs/api/java/io/Serializable.html中所述 )。 。 Unfortunately, you can't initialize val s in readObject and will have to write something like 不幸的是,您不能在readObject初始化val ,而必须编写类似

case class A() {
  private var _b = B
  def b = _b
}

If they can't, you need to store something they can be restored from in writeObject as well. 如果不能,则还需要存储一些可以writeObject还原的内容。

Finally, you can use one of the third-party serialization libraries like Kryo or Scala Pickling , because basically all of them allow to add support for types not under your control (otherwise they couldn't work with the types in standard Java library!) 最后,您可以使用第三方序列化库之一,例如KryoScala Pickling ,因为它们基本上都允许添加对不受您控制的类型的支持(否则它们将无法与标准Java库中的类型一起使用!)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM