【问题标题】:Scala: Reading a serialized object from a fileScala:从文件中读取序列化对象
【发布时间】:2011-08-27 02:50:28
【问题描述】:

我想从 Scala 中的文件中读取序列化对象,恢复类似于 Python 的 pickle 的功能。我损坏的对象读取代码如下所示:

def ReadObjectFromFile[A](filename: String): A = {
  val input = new ObjectInputStream(new FileInputStream(filename))
  val obj = input.readObject()
  obj match {
    case a: A => a
    case _ => sys.error("Type not what was expected when reading from file")
  }
}

但是,此代码会导致警告“类型模式 A 中的抽象类型 A 未选中,因为它已被擦除消除”。这样做的正确方法是什么?

【问题讨论】:

    标签: scala serialization type-erasure


    【解决方案1】:

    您可以使用隐式来绕过类型擦除,如 this blog post 中所述:

    def ReadObjectFromFile[A](filename: String)(implicit m:scala.reflect.Manifest[A]): A = {
      val input = new ObjectInputStream(new FileInputStream(filename))
      val obj = input.readObject()
      obj match {
        case x if m.erasure.isInstance(x) => x.asInstanceOf[A]
        case _ => sys.error("Type not what was expected when reading from file")
      }
    }
    

    【讨论】:

    • 博客文章链接已失效并导致垃圾邮件。
    猜你喜欢
    • 1970-01-01
    • 2019-01-19
    • 2015-04-03
    • 1970-01-01
    • 1970-01-01
    • 2013-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多