我对这些writeObject/readObject方法有些纠结。
假设我有一个
trait AbstractPosition{
def file:Path
def start:String
def end:String
}使用
class SourcePosition(val: Path, val start:String, val end:String)
extends AbstractPosition
object SourcePosition {
def apply(file: Path, start: String, end: String) =
new SourcePosition(file, start, Some(end))
def unapply(sp: SourcePosition) = Some((sp.file, sp.start, sp.end))
}我现在要把这些职位存档。由于Path对象不可序列化,朴素尝试失败:
java.io.NotSerializableException:.SourcePosition
所以我重写了:
trait AbstractPosition extends Serializable{
def file:Path
def start:String
def end:String
}
class SourcePosition(@transient var fileArg: Path, val start:String, val end:String)
extends AbstractPosition{
private var fileString :String = null
override def file: Path = this.fileArg
@throws(classOf[IOException])
private def writeObject(out: ObjectOutputStream): Unit = {
fileString = file.toString
out.defaultWriteObject()
}
@throws(classOf[IOException])
private def readObject(in: ObjectInputStream): Unit = {
in.defaultReadObject()
fileArg = Paths.get(fileString)
}
object SourcePosition {
def apply(file: Path, start: String, end: String) =
new SourcePosition(file, start, Some(end))
def unapply(sp: SourcePosition) = Some((sp.file, sp.start, sp.end))
}但徒劳无功:
sun.nio.fs.WindowsPath$WindowsPathWithAttributes :java.io.NotSerializableException
我做错了什么?
我怎样才能实现我想做的事呢?
发布于 2015-06-04 11:52:39
实际上,上面的内容似乎是可行的。
问题似乎是我忽略了使用file的val。将val更改为def允许我序列化SourcePosition
发布于 2015-06-04 09:34:58
让你的SourcePosition成为一个案例类:它是一个完美的候选人,因为它是完全不可变的。在默认情况下,Case类是一个可序列化的类,而没有所有这些writeObject/readObject内容。作为奖励,您将获得由scalac自动生成的apply/unapply方法。
https://stackoverflow.com/questions/30640006
复制相似问题