Java.io.ObjectOutputStream 的 enableReplaceObject() 方法



描述

java.io.ObjectOutputStream.enableReplaceObject(boolean enable) 方法啟用流替換流中的物件。啟用後,對於要序列化的每個物件都會呼叫 replaceObject 方法。

如果 enable 為 true,並且已安裝安全管理器,則此方法首先使用 SerializablePermission("enableSubstitution") 許可權呼叫安全管理器的 checkPermission 方法,以確保可以啟用流以替換流中的物件。

宣告

以下是 java.io.ObjectOutputStream.enableReplaceObject() 方法的宣告。

protected boolean enableReplaceObject(boolean enable)

引數

enable − boolean 引數,用於啟用物件替換。

返回值

此方法返回呼叫此方法之前之前的設定。

異常

SecurityException − 如果存在安全管理器並且其 checkPermission 方法拒絕啟用流以替換流中的物件。

示例

以下示例顯示了 java.io.ObjectOutputStream.enableReplaceObject() 方法的使用。

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);

         // enable replacing objects and return the previous setting
         System.out.println("" + oout.enableReplaceObject(true));

         // write something in the file
         oout.writeInt(i);
         oout.writeInt(1653984);
         oout.flush();

         // close the stream
         oout.close();

         // 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();
      }
   }
}

讓我們編譯並執行以上程式,這將產生以下結果:

false
319874
1653984
java_io_objectoutputstream.htm
廣告