服务热线:13616026886

技术文档 欢迎使用技术文档,我们为你提供从新手到专业开发者的所有资源,你也可以通过它日益精进

位置:首页 > 技术文档 > JAVA > 新手入门 > 基础入门 > 查看文档

编写自己的writeobject()和readobject()方法实现对象的序列化

编写自己的writeobject()和readobject()方法实现对象的序列化


// : c12:serialctl.java
// controlling serialization by adding your own
// writeobject() and readobject() methods.
// from 'thinking in java, 3rd ed.' (c) bruce eckel 2002
// www.bruceeckel.com. see copyright notice in copyright.txt.

import java.io.bytearrayinputstream;
import java.io.bytearrayoutputstream;
import java.io.ioexception;
import java.io.objectinputstream;
import java.io.objectoutputstream;
import java.io.serializable;

public class serialctl implements serializable {
  private string a;

  private transient string b;

  public serialctl(string aa, string bb) {
    a = "not transient: " + aa;
    b = "transient: " + bb;
  }

  public string tostring() {
    return a + "/n" + b;
  }

  private void writeobject(objectoutputstream streamthrows ioexception {
    stream.defaultwriteobject();
    stream.writeobject(b);
  }

  private void readobject(objectinputstream streamthrows ioexception,
      classnotfoundexception {
    stream.defaultreadobject();
    b = (stringstream.readobject();
  }

  public static void main(string[] argsthrows ioexception,
      classnotfoundexception {
    serialctl sc = new serialctl("test1""test2");
    system.out.println("before:/n" + sc);
    bytearrayoutputstream buf = new bytearrayoutputstream();
    objectoutputstream o = new objectoutputstream(buf);
    o.writeobject(sc);
    // now get it back:
    objectinputstream in = new objectinputstream(new bytearrayinputstream(
        buf.tobytearray()));
    serialctl sc2 = (serialctlin.readobject();
    system.out.println("after:/n" + sc2);
  }
///:~

扫描关注微信公众号