Item 76: Write readObject methods defensively

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.

 

你可能感兴趣的:(readObject,defensive copy)