I'd like to disable the serialization of a trait, so that all the classes that extends this trait will fail on serialization.
How can I achieve this in Scala?
I'm using spark, and I need this because the class will be very big, and serializing it will induce a performance hit, so I'd like to prevent it being serialized by mistake.
Here is my solution:
trait NonSerializable extends java.io.Externalizable {
def writeExternal(out: java.io.ObjectOutput): Unit = {
throw new UnsupportedOperationException(getClass() + " is not Serializable")
}
def readExternal(in: java.io.ObjectInput): Unit = {
throw new UnsupportedOperationException(getClass() + " is not Serializable")
}
}
case class Foo(s: String) extends NonSerializable {
}
object Foo extends App {
val bytes = new java.io.ByteArrayOutputStream
val out = new java.io.ObjectOutputStream(bytes)
out.writeObject(Foo("bar"))
}
Use Externalizable
to inject an exception in serialization. Subclass should not override readExternal
or writeExternal
.
Note: NonSerializable
violates the contract of Serializable
. I'm not sure if it can work with other libraries based on the contract of Serializable
.
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.