![](/img/trans.png)
[英]Is (or are) there a standard trait for XML and JSON serializable objects in Scala/Lift?
[英]Trait that is not serializable
我想禁用特征的序列化,以便扩展该特征的所有类在序列化时都会失败。
如何在Scala中实现这一目标?
我使用的是spark,因此我需要这样做,因为该类非常大,对其进行序列化会导致性能下降,因此,我想防止将其错误地序列化。
这是我的解决方案:
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"))
}
使用Externalizable
在序列化中注入异常。 子类不应覆盖readExternal
或writeExternal
。
注意: NonSerializable
违反了Serializable
的合同。 我不确定它是否可以根据Serializable
的合同与其他库一起使用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.