gpt4 book ai didi

java - 如何维护序列化对象的单例状态?

转载 作者:行者123 更新时间:2023-11-29 08:01:09 25 4
gpt4 key购买 nike

如果我将“A”类定义为单例,则意味着我只能创建“A”类的一个对象。如果我将它设为可序列化并序列化,那么如何实现同一对象的单例状态?

最佳答案

引用 Effective Java #77,你应该看看实现 readResolve 方法。

The readResolve feature allows you to substitute another instance for the one created by readObject [Serialization, 3.7]. If the class of an object being deserial- ized defines a readResolve method with the proper declaration, this method is invoked on the newly created object after it is deserialized. The object reference returned by this method is then returned in place of the newly created object. In most uses of this feature, no reference to the newly created object is retained, so it immediately becomes eligible for garbage collection.

public class Elvis implements Serializable {
public static final Elvis INSTANCE = new Elvis();
// readResolve for instance control - you can do better!
private Object readResolve() {
//Return the one true Elvis and let the garbage collector
// take care of the Elvis impersonator.
return INSTANCE;
}
}

关于java - 如何维护序列化对象的单例状态?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14332888/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com