`
gatusso52
  • 浏览: 109648 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

java中的clone

    博客分类:
  • java
阅读更多

1

Object中的clone(),是protected的。

 

要想调用clone()复制,需要这个对象实现Clonable接口,并覆写成public的clone

 

2

在覆写的clone中如果直接调用super。clone()

那么是浅拷贝

 

3

要进行深拷贝,则需要自己重写clone()函数

又有两种方法

a 逐个对象递归调用clone(此时要求各组件也实现Cloneable接口)

b 利用序列化(此时要求各组件也实现Serizliable接口)

 

举例

(注意Outer类中的clone的两种实现即可)

 

package simpleTest;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class MyOuter implements Cloneable,Serializable{
	private int i;
	private MyInner inner;
	public MyOuter(int i, MyInner inner) {
		super();
		this.i = i;
		this.inner = inner;
	}
	
	/**
	 * 深拷贝法一
	 */
//	@Override
//	public Object clone() throws CloneNotSupportedException{
//		MyOuter out = (MyOuter) super.clone();
//		out.inner = (MyInner)inner.clone();
//		return out;
//	}
	
	/**
	 * 深拷贝法二
	 * @throws IOException 
	 */
	@Override
	public Object clone() throws CloneNotSupportedException{
		
		try {
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			ObjectOutputStream oos;
			oos = new ObjectOutputStream(bos);
			oos.writeObject(this);
			ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
			ObjectInputStream ois =  new ObjectInputStream(bis);
			return ois.readObject();
		} catch (IOException e) {
			return null;
		} catch (ClassNotFoundException e) {
			return null;
		}
		
	}
	
	
	@Override
	public String toString(){
		return "i = " + i + " and inner.j= " + inner.getJ();
	}
	public int getI() {
		return i;
	}
	public void setI(int i) {
		this.i = i;
	}
	public MyInner getInner() {
		return inner;
	}
	public void setInner(MyInner inner) {
		this.inner = inner;
	}
	

}

class MyInner implements Cloneable,Serializable{
	private int j;
	public MyInner(int j) {
		super();
		this.j = j;
	}
	@Override
	public Object clone() throws CloneNotSupportedException{
		return super.clone();
	}
	public int getJ() {
		return j;
	}
	public void setJ(int j) {
		this.j = j;
	}
}


public class Demo {
	public static void main(String[] args) {
		MyInner inner = new MyInner(1);
		MyOuter outer = new MyOuter(2,inner);
		
		System.out.println(outer);
		
		try {
			MyOuter copy = (MyOuter) outer.clone();
			System.out.println(copy);
		} catch (CloneNotSupportedException e) {
			e.printStackTrace();
		}
	}
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics