score:-1

works if simpleclass extends serializable.

score:1

@trenobus @bluenote10 related to your findings:

i just ran into this today and i think it's because the class' name is different (mangled) when you define it in the console. for instance, i serialized a class one from scala

> import java.io._
import java.io._
> case class one(s: string, b: boolean)
defined class one
> new objectoutputstream(new fileoutputstream("data")) writeobject one("abc", true)

i then tried to deserialize it in java from the same file, having prepared a similar class named one in the top level (i made serialversionuids be the same as well, didn't include it here since it didn't matter), but got this error:

exception in thread "main" java.lang.classnotfoundexception: $line4.$read$$iw$$iw$one

suggesting that scala (rightfully) creates a new jvm class each time you define a class, and presumably keeps an internal mapping so that you can refer to it by its defined name (one).

similarly, because each such class is different in jvm, if you redefine class one in that same scala console, and then try to deserialize from the data file, you'll get an object of the original class (not of the new class that you redefined).

score:8

this solution works fine for me:

val ois = new objectinputstream(new fileinputstream(filename)) {
  override def resolveclass(desc: java.io.objectstreamclass): class[_] = {
    try { class.forname(desc.getname, false, getclass.getclassloader) }
    catch { case ex: classnotfoundexception => super.resolveclass(desc) }
  }
}

of course, when writing object, we use the same way:

val ois = new objectoutputstream(new fileoutputstream(path))
ois.writeobject(myobject)

Related Query

More Query from same tag