Effective Java 76 Write readObject methods defensively
Principle
- readObject method is effectively another public constructor, and it demands all of the same care as any other constructor. Just as a constructor must check its arguments for validity (Item 38) and make defensive copies of parameters where appropriate (Item 39), so must a readObject method.
- When an object is deserialized, it is critical to defensively copy any field containing an object reference that a client must not possess.
- Do not use the writeUnshared and readUnshared methods.
- If it is not comfortable adding a public constructor that took as parameters the values for each nontransient field in the object and stored the values in the fields with no validation, you must provide a readObject method, and it must perform all the validity checking and defensive copying that would be required of a constructor. Alternatively, you can use the serialization proxy pattern(Item 78).
/**
* @author Kaibo Hao Immutable class that uses defensive copying
*/
public final class Period implements Serializable {
private Date start;
private Date end;
/**
* @param start
* the beginning of the period
* @param end
* the end of the period; must not precede start
* @throws IllegalArgumentException
* if start is after end
* @throws NullPointerException
* if start or end is null
*/
public Period(Date start, Date end) {
this.start = new Date(start.getTime());
this.end = new Date(end.getTime());
if (this.start.compareTo(this.end) > 0)
throw new IllegalArgumentException(start + " after " + end);
}
public Date start() {
return new Date(start.getTime());
}
public Date end() {
return new Date(end.getTime());
}
public String toString() {
return start + " - " + end;
}
// Remainder omitted
// readObject method with defensive copying and validity checking
private void readObject(ObjectInputStream s) throws IOException,
ClassNotFoundException {
s.defaultReadObject();
// Defensively copy our mutable components
start = new Date(start.getTime());
end = new Date(end.getTime());
// Check that our invariants are satisfied
if (start.compareTo(end) > 0)
throw new InvalidObjectException(start + " after " + end);
}
}
Guidelines for writing a bulletproof readObject method
- For classes with object reference fields that must remain private, defensively copy each object in such a field. Mutable components of immutable classes fall into this category.
- Check any invariants and throw an InvalidObjectException if a check fails. The checks should follow any defensive copying.
- If an entire object graph must be validated after it is deserialized, use the ObjectInputValidation interface [JavaSE6, Serialization].
- Do not invoke any overridable methods in the class, directly or indirectly.
Summary
Anytime you write a readObject method, adopt the mind-set that you are writing a public constructor that must produce a valid instance regardless of what byte stream it is given. Do not assume that the byte stream represents an actual serialized instance.
Effective Java 76 Write readObject methods defensively的更多相关文章
- Effective Java 54 Use native methods judiciously
Java Native Interface(JNI) allows Java applications to call native methods, which are special method ...
- Effective Java 27 Favor generic methods
Static utility methods are particularly good candidates for generification. The type parameter list, ...
- 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 第三版——17. 最小化可变性
Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...
- 【Effective Java】阅读
Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...
- Effective Java 75 Consider using a custom serialized form
Principle Do not accept the default serialized form without first considering whether it is appropri ...
- EFFECTIVE JAVA 第十一章 系列化
EFFECTIVE JAVA 第十一章 系列化(将一个对象编码成一个字节流) 74.谨慎地实现Serializable接口 *实现Serializable接口付出的代价就是大大降低了“改变这个类 ...
随机推荐
- Python文件操作详解
Python内置了一个open()方法,用于对本地文件进行读写操作.这个功能简单.实用,属于必须掌握的基础知识. 使用open方法操作文件可以分三步走,一是打开文件,二是操作文件,三是关闭文件.下面分 ...
- AutoTransformHandler
public static ObservableCollection<F> Transform<T, F>(List<T> target) where F : ne ...
- mysql DDL时出现的锁等待状态
如下表格所示: session1: session2: 10:30:27 root@localhost:[testdb] mysql.sock>select * from t2;+------+ ...
- [SQL] SQL SERVER基础语法
Struct Query Language 1.3NF a.原子性 b.不能数据冗余 c.引用其他表的主键 2.约束 a.非空约束 b.主键约束 c.唯一约束 d.默认约束 e.检查约束 f.外键约束 ...
- 订餐APP第二次sprint+燃尽图
MY-HR 成员: 角色分配 学号 博客园 团队贡献分 围观其他小组评论 丘惠敏 PM项目经理 201406114203 http://www.cnblogs.com/qiuhuimin/ 21 ht ...
- 准备.Net转前端开发-WPF界面框架那些事,值得珍藏的8个问题
题外话 不出意外,本片内容应该是最后一篇关于.Net技术的博客,做.Net的伙伴们忽喷忽喷..Net挺好的,微软最近在跨平台方面搞的水深火热,更新也比较频繁,而且博客园的很多大牛也写的有跨平台相关技术 ...
- C#中国象棋+游戏大厅 服务器 + 客户端源码
来源:www.ajerp.com/bbs C#中国象棋+游戏大厅 服务器 + 客户端源码 源码开源 C#版中国象棋(附游戏大厅) 基于前人大虾的修改版 主要用委托实现 服务器支持在线人数,大厅桌数的设 ...
- linq之orderby子句
在Linq查询中,orderby 子句可以对查询结果集进行排序,可以升序也可以降序,排序关键字可以是多个.默认排序方式为升序. 下面的实例代码OrderQuery()中演示了orderby子句对查询的 ...
- 解决打印机报错:操作无法完成(错误0x00000709)。
解决:操作无法完成(错误0x00000709).再次检查打印机名称,并确保打印机已连接到... 上午同时说,网络打印机打印不了,于是首先看一下打印服务器IP是不是给换了,结果没换. 接着尝试重新添加一 ...
- Azure开发者任务之二:Cloud Service项目添加到ASP.Net Web中
假设我们正在把现有的Web应用程序或ASP.Net MVC Web应用程序迁移到云中.在这种情况下,我们需要把云服务添加到现有的Web应用程序或ASP.Net MVC Web应用程序中. 我们有一个W ...