使用序列化进行深拷贝

package sun.com.cn.java;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.time.LocalDate;

public class SerialCloneTest {
	public static void main(String[] args) throws CloneNotSupportedException{
		Employee harry = new Employee("Harry Hacker", 35000, 1989, 10, 1);
		
		Employee harry2 = (Employee) harry.clone();
		
		harry.raiseSalary(10);
		System.out.println(harry);
		System.out.println(harry2);
	}
}
class SerialCloneable implements Cloneable, Serializable
{
	public Object clone() throws CloneNotSupportedException
	{
		try {
			ByteArrayOutputStream bout = new ByteArrayOutputStream();
			try(ObjectOutputStream out = new ObjectOutputStream(bout))
			{
				out.writeObject(this);
			}
			try(InputStream bin = new ByteArrayInputStream(bout.toByteArray()))
			{
				ObjectInputStream in = new ObjectInputStream(bin);
				return in.readObject();
			}
		}
		catch (IOException | ClassNotFoundException e)
		{
			CloneNotSupportedException e2 = new CloneNotSupportedException();
			e2.initCause(e);
			throw e2;
		}
	}
}

class Employee extends SerialCloneable
{
	private String name;
	private double salary;
	private LocalDate hireDay;
	
	public Employee(String n, double s, int year, int month, int day)
	{
		name = n;
		salary = s;
		hireDay = LocalDate.of(year, month, day);
	}
	
	public String getName()
	{
		return name;
	}
	
	public double getSalary()
	{
		return salary;
	}
	
	public LocalDate getHireDay()
	{
		return hireDay;
	}
	
	public void raiseSalary(double byPercent)
	{
		double raise = salary * byPercent / 1000;
		salary += raise;
	}
	
	public String toString()
	{
		return getClass().getName() + "[name=" + name
				                       +",salary=" + salary
				                       + ",hireDay=" + hireDay
				                       + "]";
	}
	
}
	


通常情况下,该方式比显式地构建新对象并复制或clone数据域的克隆方法慢的多

发布了37 篇原创文章 · 获赞 5 · 访问量 5万+
展开阅读全文

没有更多推荐了,返回首页

©️2019 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

分享到微信朋友圈

×

扫一扫,手机浏览