Skip to content

Instantly share code, notes, and snippets.

@yamashiro
Created July 6, 2012 05:33
Show Gist options
  • Save yamashiro/3058277 to your computer and use it in GitHub Desktop.
Save yamashiro/3058277 to your computer and use it in GitHub Desktop.
Scalaで,Serializableじゃなくてsealedなクラスのフィールド含めてむりくりシリアライズ
、package study
import org.specs2.mutable.Specification
import scalaz.Identity
import org.sisioh.dddbase.core.Entity
import java.io._
class SerializeSpecs extends Specification {
"Serial " should {
"Some" in {
val dummy = new Dummy(Identity(1), "aaa", None, Some(Identity(3L)))
val bos = new ByteArrayOutputStream()
val oos = new ObjectOutputStream(bos)
val writeBefore = System.currentTimeMillis
oos.writeObject(dummy)
println(System.currentTimeMillis - writeBefore)
val bis = new ByteArrayInputStream(bos.toByteArray)
val ois = new ObjectInputStream(bis)
val readBefore = System.currentTimeMillis
val readDummy = ois.readObject().asInstanceOf[Dummy]
println(System.currentTimeMillis - readBefore)
readDummy.identity must_== Identity(1)
readDummy.data must_== "aaa"
readDummy.strSome must_== None
readDummy.longSome must_== Some(Identity(3L))
}
}
}
//trait IdentitySerializable[E <: Entity[ID]] extends Serializable{
// protected def writeSomeIdentity[T](f : Identity[T] => Unit) {
//
// }
//}
class Dummy(@transient val identity: Identity[Int], val data: String,
@transient val strSome : Option[Identity[String]],
@transient val longSome : Option[Identity[Long]])
extends Entity[Int] with Serializable {
@throws(classOf[IOException])
private def writeObject(out:java.io.ObjectOutputStream) : Unit = {
out.defaultWriteObject()
out.writeInt(identity.value)
strSome match {
case Some(e) => out.writeBoolean(true);out.writeUTF(e.value)
case None => out.writeBoolean(false)
}
longSome match {
case Some(e) => out.writeBoolean(true);out.writeLong(e.value)
case None => out.writeBoolean(false)
}
}
@throws(classOf[IOException])
private def readObject(in:java.io.ObjectInputStream) : Unit = {
in.defaultReadObject()
val identity = in.readInt()
val identityF = getClass.getDeclaredField("identity")
identityF.setAccessible(true)
identityF.set(this, Identity(identity))
val strF = getClass.getDeclaredField("strSome")
strF.setAccessible(true)
val strSome = in.readBoolean()
if (strSome) {
val str = in.readUTF()
strF.set(this, Some(Identity(str)))
} else {
strF.set(this, None)
}
strF.setAccessible(false)
val longF = getClass.getDeclaredField("longSome")
longF.setAccessible(true)
val longSome = in.readBoolean()
if (longSome) {
val long = in.readLong()
longF.set(this, Some(Identity(long)))
} else {
longF.set(this, None)
}
longF.setAccessible(false)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment