开发者

Which guarantees do Scala's singletons have regarding serialization?

Is it safe by default, like Java's 开发者_JAVA技巧single-element-enum pattern or is it e. g. necessary to define readResolve or similar methods somewhere to prevent accidental or malicious breakage of the singleton contract?


Yes, it is safe by default:

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

When you compile the object with scalac and decompile it (for example with JAD) you will get following Java-file:

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

    private Singleton$()
    {
    }

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜