`

Java Clone

    博客分类:
  • java
阅读更多

Clone interface: 

 

如果一个实现了Cloneable interface, 它暗示了 Object.clone() 进行 Field_to_field 复制是合法的。

 

如果一个类没有实现Cloneable 接口, 但是它调用了object.clone(),  CloneNotSupportedException being thrown

 

 

通常, 如果一个实现了Cloneanle接口, 建议大家override object.clone() 方法。

 

 

 

 Note that this interface does <i>not</i> contain the <tt>clone</tt> method.

 Therefore, it is not possible to clone an object merely by virtue of the

 fact that it implements this interface.  Even if the clone method is invoked

 reflectively, there is no guarantee that it will succeed.

 

 

public interface Cloneable { 

}

 

eg: package test.clone;

public class Person implements Cloneable{
	
	private String name;
	private String ssn;
	
	public Person(){}
	
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getSsn() {
		return ssn;
	}
	public void setSsn(String ssn) {
		this.ssn = ssn;
	}

	// 做好重写按照自己的业务需求
	@Override
	protected Object clone() throws CloneNotSupportedException {
		// TODO Auto-generated method stub
		return super.clone();
	}
	
	/**
	 * @param args
	 * @throws CloneNotSupportedException 
	 */
	public static void main(String[] args) throws CloneNotSupportedException {
		Person p = new Person();
		Person a = (Person) p.clone();
	}
}
 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics