Java ObjectInputStream .registerValidation (ObjectInputValidation obj, int prio)
Syntax
ObjectInputStream.registerValidation(ObjectInputValidation obj, int prio) has the following syntax.
public void registerValidation(ObjectInputValidation obj,
int prio)
throws NotActiveException,
InvalidObjectException
Example
In the following code shows how to use ObjectInputStream.registerValidation(ObjectInputValidation obj, int prio) method.
//from ww w. j a v a2 s . c om
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectInputValidation;
import java.io.ObjectOutputStream;
import java.io.Serializable;
public class Main {
public static void main(String[] args) throws Exception {
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStream oout = new ObjectOutputStream(out);
oout.writeObject(new Example());
oout.flush();
oout.close();
ObjectInputStream ois = new ObjectInputStream(new FileInputStream(
"test.txt"));
Example a = (Example) ois.readObject();
System.out.println(a.s);
a.validateObject();
ois.close();
}
}
class Example implements Serializable, ObjectInputValidation {
String s = "Hello World from java2s.com!";
private String readObject(ObjectInputStream in) throws IOException,
ClassNotFoundException {
ObjectInputStream.GetField gf = in.readFields();
in.registerValidation(this, 0);
return (String) gf.get("s", null);
}
public void validateObject() throws InvalidObjectException {
if (this.s.equals("Hello World!")) {
System.out.println("Validated.");
} else {
System.out.println("Not validated.");
}
}
}
The code above generates the following result.
Home »
Java Tutorial »
java.io »
Java Tutorial »
java.io »