Object readObject()
描述 (Description)
java.io.ObjectInputStream.readObject()方法从ObjectInputStream中读取一个对象。 读取对象的类,类的签名,以及类的非瞬态和非静态字段及其所有超类型的值。 可以使用writeObject和readObject方法覆盖类的默认反序列化。 这个对象引用的对象是可传递的,因此readObject可以重建完整的等效对象图。
当根对象的所有字段及其引用的对象完全恢复时,它将完全恢复。 此时,对象验证回调基于其注册的优先级按顺序执行。 回调由对象(在readObject特殊方法中)注册,因为它们是单独还原的。
对于InputStream和不应反序列化的类的问题,会抛出异常。 所有异常对InputStream都是致命的,并使其处于不确定状态; 由调用者忽略或恢复流状态。
声明 (Declaration)
以下是java.io.ObjectInputStream.readObject()方法的声明。public final Object readObject()
参数 (Parameters)
NA
返回值 (Return Value)
此方法返回从流中读取的对象。
异常 (Exception)ClassNotFoundException - 找不到序列化对象的类。
InvalidClassException - 序列化使用的类有问题。
StreamCorruptedException - 流中的控制信息不一致。
OptionalDataException - 在流中找到原始数据而不是对象。
IOException - 任何常见的输入/输出相关异常。
例子 (Example)
以下示例显示了java.io.ObjectInputStream.readObject()方法的用法。package com.iowiki;
import java.io.*;
public class ObjectInputStreamDemo {
public static void main(String[] args) {
String s = "Hello World";
byte[] b = {'e', 'x', 'a', 'm', 'p', 'l', 'e'};
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(s);
oout.writeObject(b);
oout.flush();
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
// read and print an object and cast it as string
System.out.println("" + (String) ois.readObject());
// read and print an object and cast it as string
byte[] read = (byte[]) ois.readObject();
String s2 = new String(read);
System.out.println("" + s2);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生以下结果 -Hello World
example