1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
| class DeepCloneTarget implements Serializable,Cloneable{
private String name; DeepCloneTarget(String name){ this.name = name; } public String getName() { return name; } @Override protected Object clone() throws CloneNotSupportedException { return super.clone(); } }
class Target implements Serializable,Cloneable{
private String name; public DeepCloneTarget deepCloneTarget;
Target(String name){ this.name = name; }
public String getName() { return name; } @Override protected Object clone() throws CloneNotSupportedException { Target target = null; target = (Target) super.clone(); target.deepCloneTarget = (DeepCloneTarget) deepCloneTarget.clone(); return target; } public Object deepClone() throws IOException { ByteArrayOutputStream bos = null; ObjectOutputStream oos = null; ByteArrayInputStream bis = null; ObjectInputStream ois = null;
try{ bos = new ByteArrayOutputStream(); oos = new ObjectOutputStream(bos); oos.writeObject(this);
bis = new ByteArrayInputStream(bos.toByteArray()); ois = new ObjectInputStream(bis); Target target = (Target) ois.readObject(); return target; }catch (Exception e){ e.printStackTrace(); return null; }finally { bos.close(); oos.close(); bis.close(); ois.close(); } } } public static void main(String[] args) throws CloneNotSupportedException, IOException { Target target = new Target("target"); target.deepCloneTarget = new DeepCloneTarget("deepTarget"); Target clone_target = (Target)target.clone(); Target deep_clone_target = (Target)target.deepClone(); System.out.println(clone_target.getName()+":"+clone_target.deepCloneTarget.getName()); System.out.println(deep_clone_target.getName()+":"+deep_clone_target.deepCloneTarget.getName()); }
|