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);
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值