Object Validation

Sometimes, an object will be serialized successfully and still be left in an invalid state. It may be desirable to perform some validation of one or more objects before the readObject() method of the java.io.ObjectInputStream returns the object to the caller. This validation can use any criteria that is appropriate for the class. For instance, let’s consider one of the compatible class changes mentioned earlier. If a data member is added that is an int and should have a value of either 1 or 2, we may want to perform validation in case the object was serialized from an earlier version of the class that does not contain the data member. During the validation phase, we might determine that the rest of the state of the object would be considered valid as long as we set this data member to 1. This determination might depend upon the state of other objects that are referenced. This is why the validation methods are called only after the entire object graph has been restored. Any object-specific validation that does not depend on the state of the entire object graph could be handled within the readObject() method of the specific class.

The interface java.io.ObjectInputValidation is implemented by an object that wants to participate in the validation of an object during deserialization. This interface contains one method, with the following signature:

public void validateObject()
                throws InvalidObjectException;

In order to perform object validation, the registerValidation() ...

Get Developing Java Beans now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.