Abstract interface ObjectInputValidation in Java

digitization, transformation, binary

Abstract interface ObjectInputValidation in Java

A class implements the ObjectInputValidation interface and defines the validateObject() method in order to be able to validate itself when it and all the objects it depends on have been completely deserialized from an objectInputStream. The ObjectInputValidation interface defines a callback for object validation.

The validateObject() method is only invoked, however, if the object is passed to ObjectInputStream.registerValidation();this must be done from the private readObject() method of the object.

Ads code goes here

When an object of that class is deserialized, the validateObject() method in the validation object is called. If the method is satisfied with the state of the deserialized object, it returns quietly; otherwise, it should throw an InvalidObjectException.

Note If an object is deserialized as part of a larger object graph, it’s validateObject() method is not invoked until the entire graph is read, and the original call to ObjectInputStream.readObject() is about to return.

validateObject() should throw an InvalidobjectException if the object fails validation. This stops object serialization, and causes the original call to ObjectInputStream.readObject() to terminate with the InvalidobjectException exception.

The structure of the ObjectInputValidation interface is given as

public abstract interface java.io.ObjectInputValidation{
// Public Instance Methods () 
public abstract void validateObject() throws InvalidobjectException;
}

The details of the method is given below:

public abstract void validateObject() throws InvalidobjectException 

public abstract void validateObject() throws InvalidobjectException method allows an object to check its own validity. An InvalidObjectException should be thrown if anything is invalid.

READ  Class VerifyError in Java

A snippet to use this interface ObjectInputValidation or how to use ObjectInputValidation? or how to implement ObjectInputValidation interface?


public class validator implements Serializable, ObjectInputValidation {
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
in.registerValidation(this, 0);
in.defaultReadObject();
}
public void validateObject() throws InvalidObjectException {
// if (this object is not valid)
throw new InvalidObjectException("Object not valid!");
}
...
}

Share and Enjoy !

Leave a Comment

Your email address will not be published. Required fields are marked *