Principle

  1. 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.
  2. When an object is deserialized, it is critical to defensively copy any field containing an object reference that a client must not possess.
  3. Do not use the writeUnshared and readUnshared methods.
  4. 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

  1. 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.
  2. Check any invariants and throw an InvalidObjectException if a check fails. The checks should follow any defensive copying.
  3. If an entire object graph must be validated after it is deserialized, use the ObjectInputValidation interface [JavaSE6, Serialization].
  4. 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的更多相关文章

  1. Effective Java 54 Use native methods judiciously

    Java Native Interface(JNI) allows Java applications to call native methods, which are special method ...

  2. Effective Java 27 Favor generic methods

    Static utility methods are particularly good candidates for generification. The type parameter list, ...

  3. 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 ...

  4. 《Effective Java》读书笔记 - 11.序列化

    Chapter 11 Serialization Item 74: Implement Serializable judiciously 让一个类的实例可以被序列化不仅仅是在类的声明中加上" ...

  5. Effective Java 目录

    <Effective Java>目录摘抄. 我知道这看起来很糟糕.当下,自己缺少实际操作,只能暂时摘抄下目录.随着,实践的增多,慢慢填充更多的示例. Chapter 2 Creating ...

  6. Effective Java 第三版——17. 最小化可变性

    Tips <Effective Java, Third Edition>一书英文版已经出版,这本书的第二版想必很多人都读过,号称Java四大名著之一,不过第二版2009年出版,到现在已经将 ...

  7. 【Effective Java】阅读

    Java写了很多年,很惭愧,直到最近才读了这本经典之作<Effective Java>,按自己的理解总结下,有些可能还不够深刻 一.Creating and Destroying Obje ...

  8. Effective Java 75 Consider using a custom serialized form

    Principle Do not accept the default serialized form without first considering whether it is appropri ...

  9. EFFECTIVE JAVA 第十一章 系列化

    EFFECTIVE  JAVA  第十一章  系列化(将一个对象编码成一个字节流) 74.谨慎地实现Serializable接口 *实现Serializable接口付出的代价就是大大降低了“改变这个类 ...

随机推荐

  1. BZOJ1003 物流运输 最短路+DP

    1003: [ZJOI2006]物流运输 Description 物流公司要把一批货物从码头A运到码头B.由于货物量比较大,需要n天才能运完.货物运输过程中一般要转停好几个码头.物流公司通常会设计一条 ...

  2. jQuery源码分析之=>jQuery的定义

    最近写前段的代码比较多,jQuery是用的最多的一个对象,但是之前几次看了源码,都没搞清楚jQuery是怎么定义的,今天终于看明白怎么回事了.记录下来,算是一个新的开始吧. (文中源码都是jQuery ...

  3. Winfrom中ListBox绑定List数据源更新问题

    Winfrom中ListBox绑定List数据源更新问题 摘自:http://xiaocai.info/2010/09/winform-listbox-datasource-update/ Winfr ...

  4. .NET初学者推荐课程 asp.net错误代码大全

    错误 CS0001 编译器内部错误错误 CS0003 内存溢出错误 CS0004 提升为错误的警告错误 CS0005 编译器选项后应跟正确的参数错误 CS0006 找不到动态链接的元数据文件错误 CS ...

  5. [转载]Ubuntu14.04 LTS更新源

    不同的网络状况连接以下源的速度不同, 建议在添加前手动验证以下源的连接速度(ping下就行),选择最快的源可以节省大批下载时间. 首先备份源列表: sudo cp /etc/apt/sources.l ...

  6. Wijmo金融图表系列之平均K线图&砖形图

    2015年7月16日将会发布有史以来最令人兴奋的控件-Wijmo 金融图表,它的一体化设计为单个自定义集合提供了所有主要的金融图表,这是市场上的其他控件都不具备的独一无二的好处.它像Wijmo其他任意 ...

  7. [moka同学笔记]yii表单dropdownlist样式

    <?= $form->field($modelUser,'name') ?> <div class="form-group field-community-mobil ...

  8. 数据库的sacle-up和scale-out与sharding技术区分

    scale 英文是扩展的意思. 数据库要进行扩展,指的是存储系统不够,或者性能不够,要提升的时候,就要进行扩展. 分为向上扩展和横向扩展,这就像一个人往上面发展与横向发展两种思路. scale-up: ...

  9. 写给java程序员的c++与java实现的一些重要细微差别

    0.其实常规的逻辑判断结构.工具类.文件读写.控制台读写这些的关系都不大,熟悉之后,这些都是灵活运用的问题. 学习c/c++需要预先知道的一个前提就是,虽然有ANSI C标准,但是每个c/c++编译器 ...

  10. ASP.NET MVC自定义AuthorizeAttribute篇知识点讲解—登录限制

    1.前言 a.微软对ASP.NET的开发从WebForm到MVC的转变,已经正式过去5,6个年头,现在WebForm和MVC也都越来越完善,小小算来我也已经工作了将近三年,从大学的时候学习ASP.NE ...