java 深clone和浅clone
1. clone类
public class Person implements Cloneable, Serializable{ /** * */ private static final long serialVersionUID = -1875488046285294760L; private String name; private String age; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getAge() { return age; } public void setAge(String age) { this.age = age; } public Person(String name, String age) { super(); this.name = name; this.age = age; } public Person() { super(); } @Override public String toString() { return "Person [name=" + name + ", age=" + age + "]"; } }
public class Student implements Cloneable, Serializable{ /** * */ private static final long serialVersionUID = -3295242197841442839L; private Person person; private String school; public Person getPerson() { return person; } public void setPerson(Person person) { this.person = person; } public String getSchool() { return school; } public void setSchool(String school) { this.school = school; } public Student(Person person, String school) { super(); this.person = person; this.school = school; } public Student() { super(); } /** * 深clone * @param student * @return * @throws IOException * @throws ClassNotFoundException */ public Object deepClone(Student student) throws IOException, ClassNotFoundException{ ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream ops = new ObjectOutputStream(bos); ops.writeObject(this); ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray()); ObjectInputStream ois = new ObjectInputStream(bis); return ois.readObject(); } /** * 浅clone * @param student * @return * @throws CloneNotSupportedException */ public Object clone(Student student) throws CloneNotSupportedException{ Student st = (Student) student.clone(); return st; } @Override public String toString() { return "Student [person=" + person + ", school=" + school + "]"; } }
2. 测试类
public class TestMain { public static void main(String[] args) throws CloneNotSupportedException, ClassNotFoundException, IOException { Person p = new Person("张三", "21"); Student s = new Student(p, "水木"); Student s1 = (Student) s.clone(s); Student s2 = (Student) s.deepClone(s); System.out.println(s1); System.out.println(s2); p.setAge("212"); System.out.println(s1); System.out.println(s2); } }