Object 类中的 clone 方法

发布于 2024-04-27 12:28:47 字数 2645 浏览 17 评论 0

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

关于作者

文章
评论
27 人气
更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文