简体   繁体   中英

De-/Serializing with readObject/writeObject

I'm having bit of a struggle with these writeObject/readObject methods.

Let's say I have a

trait AbstractPosition{
    def file:Path
    def start:String
    def end:String
}

with

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))
}

And that I now have to store such positions to file. The naive attempt fails because Path objects are not serializable:

java.io.NotSerializableException: ... .SourcePosition

So I rewrite:

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))
}

But to no avail:

java.io.NotSerializableException: sun.nio.fs.WindowsPath$WindowsPathWithAttributes

What am I doing wrong?

And how can I achieve what I'm trying to do?

Make your SourcePosition a case class: it's a perfect candidate as it's fully immutable. Case classes a serializable by default without all this writeObject / readObject stuff. As a bonus you will get apply / unapply methods generated automatically by scalac.

The above actually seems to work.

The problem appears to have been that I had overlooked a val using file . Changing that val to a def allowed me to serialize SourcePosition

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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