JAVA序列化的两种方式
来源:优易学  2010-1-15 12:06:50   【优易学:中国教育考试门户网】   资料下载   IT书店

  大家都知道Serializable是一个mark interface,告诉JVM这个对象可以被转换成二进制流来传输.
  Serializable 在我们实现这个接口的时候,我们可以使用4个私有方法来控制序列化的过程:
  我们来看一个例子:
  public class FooImpl implements java.io.Serializable{
  private String message;
  public String getFoo() {
  return message;
  }
  public void setMessage(String message) {
  this.message = message;
  }
  private void writeObject(java.io.ObjectOutputStream out) throws IOException {
  System.out.println("writeObject invoked");
  out.writeObject(this.message == null ? "hohohahaha" : this.message);
  }
  private void readObject(java.io.ObjectInputStream in) throws IOException,
  ClassNotFoundException {
  System.out.println("readObject invoked");
  this.message = (String) in.readObject();
  }
  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 static void main(String[] args) throws IOException,
  ClassNotFoundException {
  FooImpl fooimpl = new FooImpl();
  fooimpl.serialize();
  }
  }
  public class FooImpl implements java.io.Serializable{
  private String message;
  public String getFoo() {
  return message;
  }
  public void setMessage(String message) {
  this.message = message;
  }
  private void writeObject(java.io.ObjectOutputStream out) throws IOException {
  System.out.println("writeObject invoked");
  out.writeObject(this.message == null ? "hohohahaha" : this.message);
  }
  private void readObject(java.io.ObjectInputStream in) throws IOException,
  ClassNotFoundException {
  System.out.println("readObject invoked");
  this.message = (String) in.readObject();
  }
  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();
  }

[1] [2] 下一页

责任编辑:cyth

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