In scala, I would like to disable the Serializable trait of many case classes, since I want this class of objects to be never serialized and shipped to a remote computer in a distributed computing framework (Specifically Apache Spark), any implementation that does so should trigger an explicit runtime exception when any closure containing it is serialized.
I've tried @transient + null check, it triggers a runtime exception at deserialization (not what I want), and the error information is quite obfuscated. Is there a way to improve this?
Thanks a lot for your advice!
You can implement and mix in a trait that disables serialization:
trait NotSerializable extends Serializable {
private def writeObject(out: java.io.ObjectOutputStream): Unit = throw new NotSerializableException()
private def readObject(in: java.io.ObjectInputStream): Unit = throw new NotSerializableException()
private def readObjectNoData(): Unit = throw new NotSerializableException()
}
case class Test(foo: String) extends NotSerializable
An attempt to serialize will then throw an exception:
new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(Test("test"))
|-> java.io.NotSerializableException: A$A39$A$A39
However, what feature of case class do you actually need? The most simple solution might be to not use case classes and objects.
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.