码迷,mamicode.com
首页 > 编程语言 > 详细

java (31) - 序列化实现深克隆

时间:2015-04-21 16:08:48      阅读:182      评论:0      收藏:0      [点我收藏+]

标签:java

一.序列化:

   把对象写到流里面的过程是序列化,而把对象从流中读出来的过程叫做反序列化。在java中实现深克隆对象,常常可以先使对象实现Serializable接口,然后把对象写到一个流里面,然后再从流中读取出来,便可以重建对象。

二.序列化实现:

<strong><span style="font-size:14px;">public class Main
{
	public static void main(String[] args) throws Exception
	{
		Teacher3 t = new Teacher3();
		
		t.setAge(40);
		t.setName("Teacher Zhang");
		
		Student3 s1 = new Student3();
		
		s1.setAge(20);
		s1.setName("zhangsan");
		s1.setTeacher(t);
		
		Student3 s2 = (Student3)s1.deepCopy();
		
		System.out.println(s2.getAge());
		System.out.println(s2.getName());
		
		System.out.println("-----------------------");
		
		System.out.println(s2.getTeacher().getAge());
		System.out.println(s2.getTeacher().getName());
		
		s2.getTeacher().setAge(50);
		s2.getTeacher().setName("Teacher Li");
		
		System.out.println(s1.getTeacher().getAge());
		System.out.println(s1.getTeacher().getName());
		
		
		
		
	}
	
	
}



class Teacher3 implements Serializable
{
	private int age;
	
	private String name;

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

class Student3 implements Serializable
{
	private int age;
	
	private String name;
	
	private Teacher3 teacher;

	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 Teacher3 getTeacher()
	{
		return teacher;
	}

	public void setTeacher(Teacher3 teacher)
	{
		this.teacher = teacher;
	}
	
	public Object deepCopy() throws Exception
	{
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		
		ObjectOutputStream oos = new ObjectOutputStream(bos);
		
		oos.writeObject(this);
		
		ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
		
		ObjectInputStream ois = new ObjectInputStream(bis);
		
		return ois.readObject();
	}
}</span></strong>

打印:

20
zhangsan
-----------------------
40
Teacher Zhang
40
Teacher Zhang
三.serialVersionUID含义:

serialVersionUID是为了让该类别Serializable向后兼容。例如当你的对象序列化后存到硬盘上面后,可是后来更改了类的field(增加或减少),当你反序列化时,就会出现Exception的,这样就会造成不兼容性的问题。但当serialVersionUID相同时,它就会将不一样的field以type的缺省值Deserialize,这个可以避开不兼容性的问题。



java (31) - 序列化实现深克隆

标签:java

原文地址:http://blog.csdn.net/u010708662/article/details/45129765

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!