Object 类中的 clone 方法
clone() 方法的作用
克隆方法用于创建对象的拷贝,为了使用 clone 方法,类必须实现 java.lang.Cloneable 接口,如果没有实现 Clonebale 接口,调用父类的 clone() 方法时会抛出 CloneNotSupportedException,Cloneable 接口只是一个标识,和 Serializable
接口类似,接口中没有任何方法。
源码类似于下面这样:
protected Object clone() throws CloneNotSupportedException {
if (!(this instanceof Cloneable)) {
throw new CloneNotSupportedException("Class doesn't implement Cloneable");
}
return internalClone((Cloneable) this);
}
Object 中的 clone 方法是 protected
,也就是说这个方法只能在子类内部调用,所以我们需要在子类中写一个 public 方法,调用 Object 的 clone(),使这个方法暴露出来。
在克隆 java 对象的时候不会调用构造器。
java 提供一种叫浅拷贝(shallow copy)的默认方式实现 clone,创建好对象的副本后然后通过赋值拷贝内容,意味着如果你的类包含引用类型,那么原始对象和克隆都将指向相同的引用内容,这是很危险的,因为发生在可变的字段上任何改变将反应到他们所引用的共同内容上。为了避免这种情况,需要对引用的内容进行深度克隆。
浅拷贝
public class User implements Cloneable{
private String name;
private int age;
private int[] arr=new int[10];
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
//省略 Getter 和 Setter...
}
public class TestClone {
@Test
public void testClone(){
User user = new User();
user.setName("zhangsan");
user.setAge(18);
user.getArr()[0]=12;
try {
User clone = (User) user.clone();
System.out.println(clone.getArr()==user.getArr());//返回 true,表示两个引用都指向同一个数组
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
深拷贝
public class User implements Cloneable{
private String name;
private int age;
private int[] arr=new int[10];
public Object clone() throws CloneNotSupportedException {
User clone = (User) super.clone();
clone.setName(new String(this.name));
clone.setArr(Arrays.copyOf(this.arr,this.arr.length));
return clone;
}
//省略 Getter 和 Setter...
}
public class TestClone {
@Test
public void testClone(){
User user = new User();
user.setName("zhangsan");
user.setAge(18);
user.getArr()[0]=12;
try {
User clone = (User) user.clone();
System.out.println(clone.getArr()==user.getArr());//返回 false,表示两个引用分别指向两个不同的数组
} catch (CloneNotSupportedException e) {
e.printStackTrace();
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论