Java.io.ObjectOutputStream.annotateClass() 方法
描述
java.io.ObjectOutputStream.annotateClass(Class> cl) 可以由子类实现,以允许将类数据存储在流中。 默认情况下,此方法不执行任何操作。ObjectInputStream 中对应的方法是resolveClass。 对于流中的每个唯一类,该方法只调用一次。 类名和签名将已写入流。 此方法可以免费使用 ObjectOutputStream 来保存它认为合适的类的任何表示(例如,类文件的字节)。 ObjectInputStream 对应子类中的resolveClass 方法必须读取和使用annotateClass 写入的任何数据或对象。
声明
以下是 java.io.ObjectOutputStream.annotateClass() 方法的声明。
protected void annotateClass(Class<?> cl)
参数
cl − 为自定义数据添加注释的类。
返回值
此方法不返回值。
异常
NA
示例
下面的例子展示了 java.io.ObjectOutputStream.annotateClass() 方法的使用。
package com.tutorialspoint;
import java.io.*;
public class ObjectOutputStreamDemo extends ObjectOutputStream {
public ObjectOutputStreamDemo(OutputStream out) throws IOException {
super(out);
}
public static void main(String[] args) {
int i = 319874;
try {
// create a new file with an ObjectOutputStream
FileOutputStream out = new FileOutputStream("test.txt");
ObjectOutputStreamDemo oout = new ObjectOutputStreamDemo(out);
// write something in the file
oout.writeInt(i);
oout.writeInt(1653984);
oout.flush();
// call annotateClass but it does nothing
oout.annotateClass(Integer.class);
// create an ObjectInputStream for the file we created before
ObjectInputStream ois = new ObjectInputStream(new FileInputStream("test.txt"));
// read and print an int
System.out.println("" + ois.readInt());
// read and print an int
System.out.println("" + ois.readInt());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
让我们编译并运行上面的程序,这将产生下面的结果 −
319874 1653984

