一种java 克隆实现(二进制)

package com.ben.clone;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class Person implements Serializable
{

	private int age;

	private String name;

	private char sex;

	private List sth = new ArrayList();

	private Map bt = new HashMap();

	public int getAge()
	{
		return age;
	}

	public void setAge(int age)
	{
		this.age = age;
	}

	public String getName()
	{
		return name;
	}

	public void setName(String name)
	{
		this.name = name;
	}

	public char getSex()
	{
		return sex;
	}

	public void setSex(char sex)
	{
		this.sex = sex;
	}

	public List getSth()
	{
		return sth;
	}

	public void setSth(List sth)
	{
		this.sth = sth;
	}

	public Map getBt()
	{
		return bt;
	}

	public void setBt(Map bt)
	{
		this.bt = bt;
	}
}

 再写个类实现二进制克隆对象:

 

package com.ben.clone;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.StreamCorruptedException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class ByteCloneTest
{
	/**
	 * <pre>
	 * 以二进制方式克隆对象
	 * </pre>
	 * @param src 被克隆的对象
	 * @return 克隆的对象
	 */
	public static final Object byteClone(Object src)
	{
		try
		{
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			ObjectOutputStream out = new ObjectOutputStream(baos);
			out.writeObject(src);
			out.close();
			ByteArrayInputStream bin = new ByteArrayInputStream(baos.toByteArray());
			ObjectInputStream in = new ObjectInputStream(bin);
			Object clone = in.readObject();
			in.close();
			return (clone);
		}
		catch (ClassNotFoundException e)
		{
			throw new InternalError(e.toString());
		}
		catch (StreamCorruptedException e)
		{
			throw new InternalError(e.toString());
		}
		catch (IOException e)
		{
			throw new InternalError(e.toString());
		}
	}

	public static void main(String[] args)
	{
		Person p = new Person();
		p.setAge(80);
		p.setName("jerry");
		p.setSex('F');
		List list = new ArrayList();
		list.add("apple");
		list.add("orange");
		list.add("banana");
		Map map = new HashMap();
		map.put("哥哥", "liuliu");
		map.put("姐姐", "linlin");
		map.put("李李", "lili");
		p.setBt(map);
		p.setSth(list);
		Person ps = (Person)ByteCloneTest.byteClone(p);
		ps.setName("benlsoft");
		System.out.println("p----"+p.getName());
		System.out.println("ps---"+ps.getName());
	}
}

 发现两个克隆的对象包含的对象都不是引用对象。这样就实现了深度克隆

你可能感兴趣的:(java,apple,F#)