Brief Introduction:
Copying Java objects in a byte-stream way
Code:
Stream Clone copy function
public static object Deepclone (Object obj) {
if (obj = = null) {return
null;
}
try {
Bytearrayoutputstream byteout = new Bytearrayoutputstream ();
Object cloneobj = null;
ObjectOutputStream out = new ObjectOutputStream (byteout);
Out.writeobject (obj);
Bytearrayinputstream Bytein = new Bytearrayinputstream (Byteout.tobytearray ());
ObjectInputStream in = new ObjectInputStream (Bytein);
Cloneobj = In.readobject ();
return cloneobj;
} catch (Exception e) {
throw new RuntimeException (e);
}
}
Objectclone.java
Package test;
Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;
Import java.io.Serializable; public class Objectclone {/** * Test object/private static class person implements Serializable {p
Rivate String name;
private int age;
Person (String name, int age) {this.name = name;
This.age = age;
@Override public String toString () {return String.Format (' name:%s\nage:%s ', name, age); }/** * Test function */public static void main (string[] args) {Person person = new P
Erson ("Henry", 22);
Person Newperson = (person) objectclone.deepclone (person);
System.out.println (Newperson);
/** * Tool class * * @param obj * @return/public static object Deepclone (Object obj) { if (obj = null) {returnNull
try {bytearrayoutputstream byteout = new Bytearrayoutputstream ();
Object cloneobj = null;
ObjectOutputStream out = new ObjectOutputStream (byteout);
Out.writeobject (obj);
Bytearrayinputstream Bytein = new Bytearrayinputstream (Byteout.tobytearray ());
ObjectInputStream in = new ObjectInputStream (Bytein);
Cloneobj = In.readobject ();
return cloneobj;
catch (Exception e) {throw new RuntimeException (e);
}
}
}
Test results:
、