- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
Effective Java #77 声明我们必须使用 readResolve
来在序列化期间保留 Singleton 保证。他们用过这个例子。
public class Elvis implements Serializable{
public static final Elvis INSTANCE = new Elvis();
private Elvis() { ... }
public void leaveTheBuilding() { ... }
他们建议使用
If the Elvis class is made to implement Serializable, the following readResolve method suffices to guarantee the singleton property:
// 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; }
This method ignores the deserialized object, returning the distinguished Elvis instance that was created when the class was initialized.
最佳答案
该类仅加载一次(除非您对类加载器进行了处理,但类实际上是不同的)。上述代码的反序列化确实创建了一个新的 Elvis
。您需要使用串行代理来避免这种情况。
虽然有两个 Elvis
实例,但 Elvis.INSTANCE
只指向一个。
反序列化构造一个对象而不调用执行可序列化类的任何构造函数(但是它确实执行最派生的不可序列化基类的无参数构造函数)。
(顺便说一句,你还没有让你的类 final
,所以即使是子类也可以被反序列化。顺便说一下,你提议的 readResolve
方法不会被调用对于子类,因为它是 private
。)
关于java - Effective Java Item #77 - 单例对象的序列化 - 为什么我必须使用 readResolve?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5078785/
我最近购买了《C 编程语言》并尝试了 Ex 1-8这是代码 #include #include #include /* * */ int main() { int nl,nt,nb;
早上好!我有一个变量“var”,可能为 0。我检查该变量是否为空,如果不是,我将该变量保存在 php session 中,然后调用另一个页面。在这个新页面中,我检查我创建的 session 是否为空,
我正在努力完成 Learn Python the Hard Way ex.25,但我无法理解某些事情。这是脚本: def break_words(stuff): """this functio
我是一名优秀的程序员,十分优秀!