您的位置:首页 > 编程语言 > Java开发

java 深clone和浅clone

2014-06-26 17:59 49 查看
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);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: