每当我们需要自定义序列化机制时,都会使用外部化。如果类实现了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