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接口付出的代价就是大大降低了“改变这个类 ...
随机推荐
- 使用Eclipse调试PHP程序
我安装的是PHP Version 5.3.26,按照网上提示在Eclipse中使用XDebug进行调试,不过配置了却使用不了,下面把解决方法简要说一下. XDebug老是加载不了 From PHP 5 ...
- C# 文字转声音
添加COM组件引用:Microsoft Speech object library private SpVoice voice; private void button1_Click(object s ...
- EFcodeFirst+T4=操纵任意数据库
之前有写过两篇,EF选择Mysql数据源 跟 EF添加ADO.NET实体模型处直接选择Oracle数据源,其方便之处就不多说了,使用DBfirst直接点点点就能与数据库双向更新,而且关键是方便我们使用 ...
- [C#高级编程].NET体系结构
本章内容: 编译和运行面向 .NET的代码 MSIL的优点 值类型和引用类型 数据类型化 理解错误处理和特性 程序集..NET基类和命名空间 本章主要介绍一些概念,内容不多. C#是专门为Micros ...
- ok6410 android driver(6)
This is a short essay about the mistakes in compiling ok6410 android-2.3 source codes. If there is n ...
- Winform开发框架主界面设计展示
做了好多年Winform的程序的开发,主窗口的界面设计一般都要求做的更好一些,可以根据不同的系统功能模块进行归类整合,能使客户迅速寻找到相关功能的同时,也能感觉到整体性的美观大方,因此主窗口的界面设计 ...
- document.documentElement.clientWidth
document.documentElement.clientWidth 摘自:http://blog.sina.com.cn/s/blog_6f1f9ead0100n1f6.html 关于获取各种浏 ...
- c# dynamic动态类型和匿名类
dynamic类型 简单示例 dynamic expando = new System.Dynamic.ExpandoObject(); //动态类型字段 可读可写 expando.Id = 1; e ...
- x3dom 1.6 发布
X3DOM 库的1.6版本发布了,以下是最重要的一些变化: 完整的新的文档频道 - http://doc.x3dom.org x3dom实例频道 - http://examples.x3dom.or ...
- git 删除错误提交的commit
方法: 根据–soft –mixed –hard,会对working tree和index和HEAD进行重置: git reset --mixed:此为默认方式,不带任何参数的git reset ...