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
广告