---
title: "Item 76: Write readObject methods defensively"
author: "leonzhx"
date: "2014-05-05T10:58:55Z"
tags: ["ReadObject"]
categories: ["编程语言"]
slug: "item-76-write-readobject-methods-defensively"
draft: false
lastmod: "2014-05-05T10:58:55Z"
id: 2060014
url: "https://seanzhou.iteye.com/blog/2060014"
---

1\.  The ***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 and make defensive copies of parameters where appropriate so must a ***readObject*** method.

 

2\.  The problem arises when ***readObject*** is presented with a byte stream that is artificially constructed to generate an object that violates the invariants of its class.

 

3\.  When an object is deserialized, it is critical to defensively copy any field containing an object reference that a client must not possess. Note that the defensive copy should be performed prior to the validity check.

 

4\.  Do not use the ***writeUnshared*** and ***readUnshared*** methods. They are typically faster than defensive copying, but they don’t provide the necessary safety guarantee.

 

5\.  There is one other similarity between ***readObject*** methods and constructors, concerning nonfinal serializable classes. A ***readObject*** method must not invoke an overridable method, directly or indirectly. If this rule is violated and the method is overridden, the overriding method will run before the subclass’s state has been deserialized. A program failure is likely to result.

 

6\.  Here, in summary form, are the 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.

    4)  Do not invoke any overridable methods in the class, directly or indirectly.