Java中的Externalizable介面


當我們需要定製序列化機制時,將使用外部化。如果某個類實現了Externalizable介面,那麼物件序列化將使用writeExternal()方法執行。而在接收端當Externalizable物件是重建的例項時,將使用無參建構函式建立,然後呼叫readExternal()方法。

如果某個類只實現了Serializable介面,則將使用ObjectoutputStream執行物件序列化。在接收端,使用ObjectInputStream重建可序列化物件。

以下示例展示了Externalizable介面的用法。

示例

import java.io.Externalizable;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInput;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;

public class Tester {
   public static void main(String[] args) {

      Employee e = new Employee();
      e.name = "Reyan Ali";
      e.age = 30;
      try (
         FileOutputStream fileOut = new FileOutputStream("test.txt");
         ObjectOutputStream out = new ObjectOutputStream(fileOut);
      ) {
         out.writeObject(e);
      }catch (IOException i) {
         System.out.println(i.getMessage());
      }
      try (
         FileInputStream fileIn = new FileInputStream("test.txt");
         ObjectInputStream in = new ObjectInputStream(fileIn);
      ) {
         e = (Employee)in.readObject();
         System.out.println(e.name);
         System.out.println(e.age);
      } catch (IOException i) {
         System.out.println(i.getMessage());
      } catch (ClassNotFoundException e1) {
         System.out.println(e1.getMessage());
      }
   }
}

class Employee implements Externalizable {
   public Employee(){}
   String name;
   int age;
   public void writeExternal(ObjectOutput out) throws IOException {
      out.writeObject(name);
      out.writeInt(age);
   }
   public void readExternal(ObjectInput in) throws IOException,
   ClassNotFoundException {
      name = (String)in.readObject();
      age = in.readInt();
   }
}

這將產生以下結果−

輸出

Reyan Ali
30

更新於:2020年6月21日

1000多次瀏覽

開啟你的職業生涯

完成課程即可獲得認證

開始
廣告