|
| 1 | +package btp.oneP; |
| 2 | + |
| 3 | +import java.io.ByteArrayInputStream; |
| 4 | +import java.io.ByteArrayOutputStream; |
| 5 | +import java.io.IOException; |
| 6 | +import java.io.ObjectInputStream; |
| 7 | +import java.io.ObjectOutputStream; |
| 8 | +import java.io.Serializable; |
| 9 | + |
| 10 | +public class DeepClone implements Serializable,Cloneable{ |
| 11 | + |
| 12 | + /** |
| 13 | + * |
| 14 | + */ |
| 15 | + private static final long serialVersionUID = 1L; |
| 16 | + |
| 17 | + private String name; |
| 18 | + private DeepClone son; |
| 19 | + public String getName() { |
| 20 | + return name; |
| 21 | + } |
| 22 | + public void setName(String name) { |
| 23 | + this.name = name; |
| 24 | + } |
| 25 | + public DeepClone getSon() { |
| 26 | + return son; |
| 27 | + } |
| 28 | + public void setSon(DeepClone son) { |
| 29 | + this.son = son; |
| 30 | + } |
| 31 | + |
| 32 | + public DeepClone(String name) { |
| 33 | + super(); |
| 34 | + this.name = name; |
| 35 | + } |
| 36 | + public DeepClone deepClone() throws IOException, ClassNotFoundException { |
| 37 | + ByteArrayOutputStream bos = new ByteArrayOutputStream(); |
| 38 | + ObjectOutputStream oos = new ObjectOutputStream(bos); |
| 39 | + oos.writeObject(this); |
| 40 | + ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); |
| 41 | + ObjectInputStream ois = new ObjectInputStream(bis); |
| 42 | + return (DeepClone)ois.readObject(); |
| 43 | + } |
| 44 | + |
| 45 | + @Override |
| 46 | + public String toString() { |
| 47 | + return "DeepClone [name=" + name + ", son=" + son + "]"; |
| 48 | + } |
| 49 | + public static void main(String[] args) throws ClassNotFoundException, IOException, CloneNotSupportedException { |
| 50 | + DeepClone f = new DeepClone("father"); |
| 51 | + f.setSon(new DeepClone("son")); |
| 52 | + DeepClone clone = f.deepClone(); |
| 53 | + System.out.println("É±´£º"+clone); |
| 54 | + System.out.println(clone.getSon() == f.getSon()); |
| 55 | + DeepClone ff = (DeepClone)f.clone(); |
| 56 | + System.out.println("dz¿½±´£º"+ff); |
| 57 | + System.out.println(ff.getSon() == f.getSon()); |
| 58 | + } |
| 59 | + |
| 60 | +} |
0 commit comments