Serializable与Externalizable的区别
来源:优易学  2011-11-13 17:09:12   【优易学:中国教育考试门户网】   资料下载   IT书店

 

  public class FooImpl implements java.io.Externalizable {

  private String message;

  public String getFoo() {

  return message;

  }

  public void setMessage(String message) {

  this.message = message;

  }

  private Object writeReplace() throws ObjectStreamException {

  System.out.println("writeReplace invoked");

  return this;

  }

  private Object readResolve() throws ObjectStreamException {

  System.out.println("readResolve invoked");

  return this;

  }

  public Object serialize() throws IOException, ClassNotFoundException {

  ByteArrayOutputStream baos = new ByteArrayOutputStream();

  ObjectOutputStream oos = new ObjectOutputStream(baos);

  oos.writeObject(this);

  ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());

  ObjectInputStream ois = new ObjectInputStream(bais);

  return ois.readObject();

  }

  public void readExternal(ObjectInput arg0) throws IOException,

  ClassNotFoundException {

  System.out.println("readExternal invoked");

  Object obj = arg0.readObject();

  }

  public void writeExternal(ObjectOutput arg0) throws IOException {

  System.out.println("writeExternal invoked");

  arg0.writeObject("Hello world");

  }

  public static void main(String[] args) throws IOException,

  ClassNotFoundException {

  FooImpl fooimpl = new FooImpl();

  fooimpl.serialize();

  }

  }

  我们运行这段代码看到的debug信息:

  writeReplace invoked

  writeExternal invoked

  readExternal invoked

  readResolve invoked

  在此writeExternal 和readExternal 的作用与writeObject和readObject 一样.

  最后,当我们同时实现了两个interface的时候,JVM只运行Externalizable 接口里面的writeExternal 和readExternal 方法对序列化内容进行处理.

  需要注意的是:Serializable是一个真正的mark interface,

  writeObject,readObject, writeReplace,readResolve是直接与JVM通信,告诉JVM序列化的内容.

上一页  [1] [2] 

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训