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 − 要為其註釋自定義資料的類。

返回值

此方法不返回值。

異常

示例

以下示例演示了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
java_io_objectoutputstream.htm
廣告