// : 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 stream) throws ioexception { stream.defaultwriteobject(); stream.writeobject(b); }
private void readobject(objectinputstream stream) throws ioexception, classnotfoundexception { stream.defaultreadobject(); b = (string) stream.readobject(); }
public static void main(string[] args) throws 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 = (serialctl) in.readobject(); system.out.println("after:/n" + sc2); } } ///:~
|