ObjectInputStream registerValidation()方法
java.io.ObjectInputStream.registerValidation(ObjectInputValidation obj, int prio) 方法用于注册对象的图形被返回之前进行验证。虽然类似resolveObject这些验证被称为整个图形被改组之后。通常情况下,一个readObject方法将注册对象,这样,当所有的对象都恢复了最后一组的验证可以进行数据流。
1 语法
public void registerValidation(ObjectInputValidation obj, int prio)
2 参数
obj:接收验证回调的对象。
prio:控制回调的顺序,0是一个很好的默认值。使用更高的数字被称为背前面,较小的数字后回调。在一个优先级,回调在没有特定的顺序进行处理。
3 返回值
无
4 示例
package com.yiidian;
/**
* 一点教程网: http://www.yiidian.com
*/
/**
* java.io.ObjectInputStream.registerValidation(ObjectInputValidation obj, int prio)方法的例子
*/
import java.io.*;
public class Demo {
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.");
}
}
}
}
输出结果为:
Hello World!
Validating object...
Validated.
热门文章
优秀文章