case类private构造函数 - 需要readResolve实现 [英] case class private constructor - need for readResolve implementation
问题描述
我只是googling来找出如何创建一个case类与私人构造函数。以下是
I was just googling to find out how to create a case class with private constructor. Below is the correct way for doing this as described in
object A {
def apply(s: String, i: Int): A =
new A(s.toUpperCase, i) {} //abstract class implementation intentionally empty
}
abstract case class A private[A] (s: String, i: Int) {
private def readResolve(): Object = //to ensure validation and possible singleton-ness, must override readResolve to use explicit companion object apply method
A.apply(s, i)
def copy(s: String = s, i: Int = i): A =
A.apply(s, i)
}
下面是我的理解: -
Below is my understanding so far :-
如果我们声明一个case类抽象,那么编译器不会生成copy和apply方法的实现。
If we declare a case class abstract, then implementation for copy and apply method will not be generated by the compiler.
问题,我正在努力: -
Below is the question, that I am struggling with :-
为什么需要提供readResolve的实现?
Why it is required to provide implementation of readResolve ?
推荐答案
readResolve实现是通过编辑类的序列化副本来防止创建案例类的无效实例。
The readResolve implementation is there to prevent the creation of invalid instances of the case class by editing serialised copies of the class.
这是因为case类扩展了 Serializable
,因此可能最终得到序列化并写入文件(或DB,或任何位置)。此时,可以编辑文件/ DB /中的序列化副本以创建无效值(例如,使 s
小写)。在反序列化时,'live'实例将无效,除非重写序列化过程中使用的 readResolve
方法以防止这种情况。
It comes about because case classes extend Serializable
, and so may end up getting serialised and written out to file (or DB, or wherever). At this point the serialised copy in the file/DB/wherever could be edited to create an invalid value (eg. making s
lower case). On deserialising back, the 'live' instance will then be invalid, unless the readResolve
method that is used in the deserialisation process is overriden to prevent this.
这篇关于case类private构造函数 - 需要readResolve实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!