Scala 的单例在序列化方面有哪些保证?

默认情况下它是否安全,就像Java的单元素枚举模式一样,或者例如,有必要在某个地方定义或类似的方法以防止意外或恶意破坏单例契约?readResolve


答案 1

是的,默认情况下它是安全的:

object Singleton extends Serializable
// with Scala 2.8: @serializable object Singleton

import java.io._

val out = new ObjectOutputStream(new FileOutputStream("singleton"))
out.writeObject(Singleton)
out.close

val in = new ObjectInputStream(new FileInputStream("singleton"))
val obj = in.readObject
in.close

obj == Singleton // should print true

当你用 scalac 编译对象并反编译它(例如使用 JAD)时,你会得到以下 Java-file:

public final class Singleton$ implements Serializable, ScalaObject
{
    public Object readResolve()
    {
        return MODULE$;
    }

    private Singleton$()
    {
    }

    public static final Singleton$ MODULE$ = new Singleton$1();
}

答案 2