Effective Java 77 For instance control, prefer enum types to 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 deserialized 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 {
/**
* The version UID for the serial version object.
*/
private static final long serialVersionUID = 4285474589312744336L;
public static final Elvis INSTANCE = new Elvis();
private 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;
}
public static void main(String[] args) {
ByteArrayOutputStream os = new ByteArrayOutputStream();
ObjectOutputStream oos;
try {
oos = new ObjectOutputStream(os);
oos.writeObject(Elvis.INSTANCE);
oos.close();
ByteArrayInputStream is = new ByteArrayInputStream(os.toByteArray());
ObjectInputStream ois = new ObjectInputStream(is);
Elvis e = (Elvis) ois.readObject();
System.out.printf("Elvis is %s the one used before? ",
e == Elvis.INSTANCE? "": "not");
ois.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Note
If you depend on readResolve for instance control, all instance fields with object reference types must be declared transient. If a singleton contains a nontransient object reference field, the contents of this field will be deserialized before the singleton's readResolve method is run.
A demo for attack to secure a reference to the deserialized object before its readResolve method is run.
First, write a "stealer" class that has both a readResolve method and an instance field that refers to the serialized singleton in which the stealer "hides." In the serialization stream, replace the singleton's nontransient field with an instance of the stealer. You now have a circularity: the singleton contains the stealer and the stealer refers to the singleton.
Because the singleton contains the stealer, the stealer's readResolve method runs first when the singleton is deserialized. As a result, when the stealer's readResolve method runs, its instance field still refers to the partially deserialized (and as yet unresolved) singleton.
The stealer's readResolve method copies the reference from its instance field into a static field, so that the reference can be accessed after the readResolve method runs. The method then returns a value of the correct type for the field in which it's hiding. If it didn't do this, the VM would throw a ClassCastException when the serialization system tried to store the stealer reference into this field.
// Broken singleton - has nontransient object reference field!
public class Elvis implements Serializable {
private static final long serialVersionUID = 1L;
public static final Elvis INSTANCE = new Elvis();
private Elvis() {
}
private String[] favoriteSongs = { "Hound Dog", "Heartbreak Hotel" }; // favorite field
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
private Object readResolve() throws ObjectStreamException {
return INSTANCE;
}
}
public class ElvisStealer implements Serializable {
static Elvis impersonator;
private Elvis payload;
private Object readResolve() {
// Save a reference to the "unresolved" Elvis instance
impersonator = payload;
// Return an object of correct type for favorites field
return new String[] { "A Fool Such as I" };
}
private static final long serialVersionUID = 0;
}
You could fix the problem by declaring the favorites field transient, but you're better off fixing it by making Elvis a single-element enum type (Item 3).
// Enum singleton - the preferred approach
public enum Elvis {
INSTANCE;
private String[] favoriteSongs = { "Hound Dog", "Heartbreak Hotel" };
public void printFavorites() {
System.out.println(Arrays.toString(favoriteSongs));
}
}
The accessibility of readResolve is significant.
If you place a readResolve method on a final class, it should be private.
If you place a readResolve method on a nonfinal class, you must carefully consider its accessibility.
If it is private, it will not apply to any subclasses.
If it is package-private, it will apply only to subclasses in the same package.
If it is protected or public, it will apply to all subclasses that do not override it.
If a readResolve method is protected or public and a subclass does not overriden it, deserializing a serialized subclass instance will produce a superclass instance, which is likely to cause a ClassCastException.
Summary
You should use enum types to enforce instance control invariants wherever possible. If this is not possible and you need a class to be both serializable and instance-controlled, you must provide a readResolve method and ensure that all of the class's instance fields are either primitive or transient.
Effective Java 77 For instance control, prefer enum types to readResolve的更多相关文章
- Effective Java 31 Use instance fields instead of ordinals
Principle Never derive a value associated with an enum from its ordinal; store it in an instance fie ...
- Effective Java 19 Use interfaces only to define types
Reason The constant interface pattern is a poor use of interfaces. That a class uses some constants ...
- Effective Java 37 Use marker interfaces to define types
Marker interface is an interface that contains no method declarations, but merely designates (or &qu ...
- Effective Java Index
Hi guys, I am happy to tell you that I am moving to the open source world. And Java is the 1st langu ...
- 《Effective Java》读书笔记 - 11.序列化
Chapter 11 Serialization Item 74: Implement Serializable judiciously 让一个类的实例可以被序列化不仅仅是在类的声明中加上" ...
- Effective Java 目录
<Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 第二版 Enum
/** * Effective Java 第二版 * 第30条:用enum代替int常量 */ import java.util.HashMap;import java.util.Map; publi ...
- Effective Java Chapter4 Classes and Interface
MInimize the accessibility of classes and members 这个叫做所谓的 information hiding ,这么做在于让程序耦合度更低,增加程序的健壮性 ...
随机推荐
- 鼠标经过(hover)事件的延时处理
关于鼠标hover事件及延时 鼠标经过事件为web页面上最常见的事件之一.简单的hover可以用CSS :hover伪类实现,复杂点的用js. 一般情况下,我们是不对鼠标hover事件进行延时处理.但 ...
- HashMap的实现原理
1.HashMap的数据结构 数组的特点是:寻址容易,插入和删除困难:而链表的特点是:寻址困难,插入和删除容易.那么我们能不能综合两者的特性,做出一种寻址容易,插入删除也容易的数据结构?答案是肯定的, ...
- Oracle工程建设行业解决方案
为何选择Oracle工程建设行业解决方案? Oracle为工程建设企业提供一套全面.开放且集成的业务管理软件.服务器和存储解决方案.这些解决方案经过集成设计,能够实现卓越性能,从而优化业务的方方面面. ...
- java操作小技巧,遇到过的会一直更新,方便查找
1.<c:forEach>可以循环map array List 2.操纵数组,不知道类型的情况下,不需要判断数组类型,直接用反射,arrays.Class.isArrays() 获取数组长 ...
- c++中stl容器的常用示例
1. set(集合)——包含了经过排序了的数据,这些数据的值(value)必须是唯一的. 也就是说输入set容器后得到数据,会去重并排序. s.insert()插入一个元素 s.begin ...
- mfc110.dll丢失,解决方法
mfc110.dll下载_附文件使用方法 mfc110.dll是存放在windows系统中的一个重要dll文件,缺少它可能会造成部分软件或游戏无法正常运行.当系统提示“没有找到mfc110.dll”或 ...
- CentOS 编译安装 MySQL5.7
下载 所有版本下载地址: http://dev.mysql.com/downloads/mysql/ 此处用 5.7.10 wget http://dev.mysql.com/get/Download ...
- Android 手机卫士12--进程管理
1.本进程不能被选中,所以先将checkbox隐藏掉--手机卫士 不能自杀 if(getItem(position).packageName.equals(getPackageName())){ ho ...
- parseInt第二个参数详解
前阵子在stackOverflow上看到两个这样的问题: 为什么parseInt(8,3) == NaN,parseInt(16,3) == 1? 为什么parseInt('dsff66',16) = ...
- 初学Node(二)package.json文件
package.json简介 package.json在Node项目中用于描述项目的一些基本信息,以及依赖的配置,一般每一个Node项目的根目录下都有一个package.json文件. 在项目的根目录 ...