How to make case classes / objects non-serializable in scala? annotations / traits / auxiliary works

In scala, I would like to disable the Serializable property for many case classes, since I want this class of objects to never be serialized and sent to a remote computer in a distributed computing environment (specifically Apache Spark), any implementation that does this, should throw an explicit exception at runtime when any closure containing it is serialized.

I tried @transient + null check, it raises an exception at runtime during deserialization (not what I want), and the error information is pretty confusing. Is there any way to improve this?

Thanks so much for your advice!

+4
source share
1 answer

You can implement and shuffle in a tag 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

The serialization attempt then throws an exception:

new ObjectOutputStream(new ByteArrayOutputStream()).writeObject(Test("test"))
|-> java.io.NotSerializableException: A$A39$A$A39

However, what feature of the case class do you really need? The simplest solution might not be to use classes and class objects .

+5
source

All Articles