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. 【Spark】---- Spark 硬件配置

    存储系统 Spark任务需要从一些外部的存储系统加载数据(如:HDFS 或者 HBase),重要的是存储系统要接近Spark系统,我们有如下推荐:   (1)如果可能,运行Spark在相同的HDFS节 ...

  2. EntityFramework 6.1.2-beta2

    EntityFramework 6.1.2-beta2 Entity Framework is Microsoft's recommended data access technology for n ...

  3. php配合jquery实现增删操作

    后台使用php,前台引用jquery,实现增删操作,代码如下: <script type="text/javascript" src="http://keleyi. ...

  4. 第一个app.总结

    前记: 最近想整点外快,但是又没啥子技术,唉,学了一下android,想写点游戏啥的,,唉,可惜,美工,UI始终不行,代码也勉勉强强... 不过总的来说也是收获参半吧,也是有一些新的知识学到了嘛,至少 ...

  5. Fluent NHibernate other example

    测试用的当前最新版本: sql: --- CREATE TABLE Users ( UserID INT IDENTITY(1,1) PRIMARY KEY, [Name] VARCHAR(50) N ...

  6. Servlet3.0 Test

    1. Servlet3.0 Test and Annotation used 你可以从tomcat7中lib文件夹中找到servlet-api.jar package com.goodfan.serv ...

  7. php生成静态文件

    1,通用生成方法 //获取文件内容 $content=file_get_contents("http://www.google.com/" ); $id=110; $filenam ...

  8. 【FFmpeg】ffplay播放rtsp视频流花屏问题

    问题描述:ffplay播放rtsp视频流时,播放过程中随机出现花屏现象. 基本流程学习:阅读ffplay源码,熟悉其播放rtsp视频流的基本流程. 在ffplay源码阅读和分析的基础上,画出了其播放r ...

  9. WCF实战2

    上一篇中,我们创建了一个简单的WCF服务,在测试的时候,我们使用VS2008自带的WCFSVCHost(WCF服务主机)发布WCF服务,以便进行测试.这种VS2008内置的WCFSVCHost只适用于 ...

  10. ECMAScript 6学习笔记(一):展开运算符

    同步发布于:https://mingjiezhang.github.io/(转载请说明此出处). JavaScript是ECMAScript的实现和扩展,ES6标准的制定也为JavaScript加入了 ...