Skip to content

Instantly share code, notes, and snippets.

@skp33
Forked from ramn/Deserialization.scala
Created April 6, 2018 18:22
Show Gist options
  • Save skp33/7909b71cef14b4aa05e240bfe6fc0a47 to your computer and use it in GitHub Desktop.
Save skp33/7909b71cef14b4aa05e240bfe6fc0a47 to your computer and use it in GitHub Desktop.
Object serialization example in Scala
import java.io._
@SerialVersionUID(15L)
class Animal(name: String, age: Int) extends Serializable {
override def toString = s"Animal($name, $age)"
}
case class Person(name: String)
// or fork := true in sbt
class ObjectInputStreamWithCustomClassLoader(
fileInputStream: FileInputStream
) extends ObjectInputStream(fileInputStream) {
override def resolveClass(desc: java.io.ObjectStreamClass): Class[_] = {
try { Class.forName(desc.getName, false, getClass.getClassLoader) }
catch { case ex: ClassNotFoundException => super.resolveClass(desc) }
}
}
object MyDeserialize extends App {
val fis = new FileInputStream("../a.tmp")
val ois = new ObjectInputStreamWithCustomClassLoader(fis)
val animal = ois.readObject
val person = ois.readObject
ois.close
println(animal)
println(person)
}
import java.io.FileOutputStream
import java.io.ObjectOutputStream
@SerialVersionUID(15L)
class Animal(name: String, age: Int) extends Serializable {
override def toString = s"Animal($name, $age)"
}
case class Person(name: String) extends Serializable
object MySerialize extends App {
val fos = new FileOutputStream("../a.tmp")
val oos = new ObjectOutputStream(fos)
oos.writeObject(new Animal("Dvorak", 12))
oos.writeObject(Person("Dijkstra"))
oos.close
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment