Java.io.ObjectInputStream.registerValidation() Method
Description
The java.io.ObjectInputStream.registerValidation(ObjectInputValidation obj, int prio) method is used to register an object to be validated before the graph is returned. While similar to resolveObject these validations are called after the entire graph has been reconstituted. Typically, a readObject method will register the object with the stream so that when all of the objects are restored a final set of validations can be performed.
Declaration
Following is the declaration for java.io.ObjectInputStream.registerValidation() method
public void registerValidation(ObjectInputValidation obj, int prio)
Parameters
obj -- the object to receive the validation callback.
prio -- controls the order of callbacks;zero is a good default. Use higher numbers to be called back earlier, lower numbers for later callbacks. Within a priority, callbacks are processed in no particular order.
Return Value
This method does not return a value.
Exception
NotActiveException -- The stream is not currently reading objects so it is invalid to register a callback.
InvalidObjectException -- The validation object is null.
Example
The following example shows the usage of java.io.ObjectInputStream.registerValidation() method.
package com.tutorialspoint;
import java.io.*;
public class ObjectInputStreamDemo {
public static void main(String[] args) {
try {
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
// write something in the file
oout.writeObject(new Example());
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois =
new ObjectInputStream(new FileInputStream("test.txt"));
// read the object and print the string
Example a = (Example) ois.readObject();
// print the string that is in Example class
System.out.println("" + a.s);
// validate the object
a.validateObject();
} catch (Exception ex) {
ex.printStackTrace();
}
}
static class Example implements Serializable, ObjectInputValidation {
String s = "Hello World!";
private String readObject(ObjectInputStream in)
throws IOException, ClassNotFoundException {
// call readFields in readObject
ObjectInputStream.GetField gf = in.readFields();
// register validation for the object
in.registerValidation(this, 0);
// save the string and return it
return (String) gf.get("s", null);
}
public void validateObject() throws InvalidObjectException {
System.out.println("Validating object...");
if (this.s.equals("Hello World!")) {
System.out.println("Validated.");
} else {
System.out.println("Not validated.");
}
}
}
}
Let us compile and run the above program, this will produce the following result:
Hello World! Validating object... Validated.