阅读 27

JDK源码阅读笔记-Cloneable接口

JDK 版本:1.8

代码地址

欢迎关注我的公众号:月光自习室

1.前言

clone方法能方便的获得一个对象的拷贝,但其中也有些细节需要注意。

2.实现注意事项

2.1 要调用 clone 方法必须实现 Cloneable 接口

如果类没有实现 Cloneable 接口,类的实例却调用了 clone 方法,则会抛出CloneNotSupportedException异常。

用反射机制去调用 Objec 类的 clone 方法,可以观察到这个现象:

Object object = new Object();
Method method = object.getClass().getDeclaredMethod("clone");
method.setAccessible(true);
method.invoke(object);
复制代码

运行结果:

Caused by: java.lang.CloneNotSupportedException: java.lang.Object
	at java.lang.Object.clone(Native Method)
复制代码
2.2 clone 方法的默认实现是浅拷贝

clone 方法的默认实现是拷贝,即对于类中可变对象没有进行真正的拷贝,只是将该可变对象赋值给了克隆对象对应的字段。修改当前对象中可变对象也会影响到克隆对象中相应的字段。

举个例子来说明下:

private static void shallowCopyTest() {
    Person ming = new Person("ming", new String[]{"mingMing", "daMing"});
    compareCloneObject(ming);
}

private static void compareCloneObject(Person person) {
    try {
        Person fakePerson = (Person) person.clone();
        System.out.println("person.getNickName() == fakePerson.getNickName() : "
                + (person.getNickName() == fakePerson.getNickName()));
        fakePerson.setNickName(0, "compare");
        System.out.println(person);
        System.out.println(fakePerson);
    } catch (CloneNotSupportedException e) {
        e.printStackTrace();
    }
}

private static class Person implements Cloneable {
    private String name;
    private String[] nickName;

    public Person(String name, String[] nickName) {
        this.name = name;
        this.nickName = nickName;
    }

    public void setNickName(int index, String nickName) {
        this.nickName[index] = nickName;
    }

    public void setNickName(String[] nickName) {
        this.nickName = nickName;
    }

    public String[] getNickName() {
        return nickName;
    }

    @Override
    public Object clone() throws CloneNotSupportedException {
        return super.clone();
    }

    @Override
    public String toString() {
        return "Person{" +
                "name='" + name + '\'' +
                ", nickName=" + Arrays.toString(nickName) +
                '}';
    }
}
复制代码

调用shallowCopyTest方法,输出结果为:

person.getNickName() == fakePerson.getNickName() : true
Person{name='ming', nickName=[compare, daMing]}
Person{name='ming', nickName=[compare, daMing]}
复制代码

可以看到原对象与克隆对象的 nickName 是同一个数组,更改一个以后另一个的值也发送相应变化。

2.3 深拷贝的实现

实现深拷贝要将对象类的所有可变对象都拷贝一遍,然后用拷贝的引用去替换掉原有的引用。

实现例子如下:

private static void deepCopyTest() {
    Student ming = new Student("ming", new String[]{"mingMing", "daMing"}, "jiangNan");
    compareCloneObject(ming);
}

public static class Student extends Person {
        private String school;

        public Student(String name, String[] nickName, String school) {
            super(name, nickName);
            this.school = school;
        }

        @Override
        public Object clone() throws CloneNotSupportedException {
            Student student = (Student) super.clone();
            student.setNickName(this.getNickName().clone());
            return student;
        }

        @Override
        public String toString() {
            return "Student{" +
                    "name='" + super.name + '\'' +
                    ", nickName=" + Arrays.toString(super.nickName) +
                    ", school='" + school + '\'' +
                    '}';
        }
    }
复制代码

调用deepCopyTest方法,输出结果为:

person.getNickName() == fakePerson.getNickName() : false
Student{name='ming', nickName=[mingMing, daMing], school='jiangNan'}
Student{name='ming', nickName=[compare, daMing], school='jiangNan'}
复制代码

可以看到两个对象 nickName 已经不是同一个对象了,改变之后也不会相互影响了。这是因为在覆写的 clone 方法中对 nickName 数组也进行了克隆,并赋值给克隆对象。

3.注释文档及个人翻译

/**
 * A class implements the <code>Cloneable</code> interface to
 * indicate to the {@link java.lang.Object#clone()} method that it
 * is legal for that method to make a
 * field-for-field copy of instances of that class.
 * <p>
 * 一个类实现了 Cloneable 接口表示该类使用clone()方法来实现实例的逐字段的复制是合法的。
 * 
 * Invoking Object's clone method on an instance that does not implement the
 * <code>Cloneable</code> interface results in the exception
 * <code>CloneNotSupportedException</code> being thrown.
 * <p>
 * 在一个没有实现 Cloneable 接口的实例上调用 clone 方法将会抛出CloneNotSupportedException。
 * 
 * By convention, classes that implement this interface should override
 * <tt>Object.clone</tt> (which is protected) with a public method.
 * See {@link java.lang.Object#clone()} for details on overriding this
 * method.
 * 按照惯例,实现该接口的类应该覆写Object.clone为一个公共方法。查看java.lang.Object#clone()
 * 来获取更多细节。
 * 
 * <p>
 * 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.
 * 注意:本接口不包含 clone 方法。因此,不能仅凭仅仅实现了本接口来克隆对象,即使是反射式调用,
 * 也不能保证成功。
 * @author  unascribed
 * @see     java.lang.CloneNotSupportedException
 * @see     java.lang.Object#clone()
 * @since   JDK1.0
 */
复制代码
/**
 * Creates and returns a copy of this object.  The precise meaning
 * of "copy" may depend on the class of the object. The general
 * intent is that, for any object {@code x}, the expression:
 * <blockquote>
 * <pre>
 * x.clone() != x</pre></blockquote>
 * will be true, and that the expression:
 * <blockquote>
 * <pre>
 * x.clone().getClass() == x.getClass()</pre></blockquote>
 * will be {@code true}, but these are not absolute requirements.
 * While it is typically the case that:
 * <blockquote>
 * <pre>
 * x.clone().equals(x)</pre></blockquote>
 * will be {@code true}, this is not an absolute requirement.
 * <p>
 * 创建并返回一个对象的拷贝。拷贝的准确定义取决于对象的类定义。普遍的来说,对任意对象 x,
 * 表达式:x.clone() ! = x 的值是 true,并且表达式:x.clone().getClass() == x.getClass() 
 * 的值是
 * true,但这些要求并不是绝对的。并且通常表达式:x.clone().equals(x)的值也是 true,
 * 这也不是绝对必要的条件。
 * 
 * By convention, the returned object should be obtained by calling
 * {@code super.clone}.  If a class and all of its superclasses (except
 * {@code Object}) obey this convention, it will be the case that
 * {@code x.clone().getClass() == x.getClass()}.
 * <p>
 * 按照惯例,应该通过调用 super.clone 来获取返回的对象。如果一个类及其所有超类(Object 除外)
 * 都遵循此约定,则 x.clone().getClass() == x.getClass() 成立。
 * 
 * By convention, the object returned by this method should be independent
 * of this object (which is being cloned).  To achieve this independence,
 * it may be necessary to modify one or more fields of the object returned
 * by {@code super.clone} before returning it.  Typically, this means
 * copying any mutable objects that comprise the internal "deep structure"
 * of the object being cloned and replacing the references to these
 * objects with references to the copies.  If a class contains only
 * primitive fields or references to immutable objects, then it is usually
 * the case that no fields in the object returned by {@code super.clone}
 * need to be modified.
 * <p>
 * 按照惯例,被本方法返回的对象应该与被克隆的原本对象无关。为了实现这种独立,可能需要在
 * 克隆方法返回前修改被返回对象的字段。通常,这意味着拷贝构成被克隆对象的内部“深度结构”
 * 的任何可变对象,并用拷贝的引用替换掉原本对象的引用。如果一个类仅仅包含原始字段或不可
 * 变对象的引用,那么通常super.clone返回对象中没有字段需要被修改。
 * 
 * The method {@code clone} for class {@code Object} performs a
 * specific cloning operation. First, if the class of this object does
 * not implement the interface {@code Cloneable}, then a
 * {@code CloneNotSupportedException} is thrown. Note that all arrays
 * are considered to implement the interface {@code Cloneable} and that
 * the return type of the {@code clone} method of an array type {@code T[]}
 * is {@code T[]} where T is any reference or primitive type.
 * Otherwise, this method creates a new instance of the class of this
 * object and initializes all its fields with exactly the contents of
 * the corresponding fields of this object, as if by assignment; the
 * contents of the fields are not themselves cloned. Thus, this method
 * performs a "shallow copy" of this object, not a "deep copy" operation.
 * <p>
 * Object 类的 clone 方法执行特定的克隆操作。首先,如果对象的类没有实现 Cloneable 
 * 接口,那么会抛出 CloneNotSupportedException 异常。请注意,所有的数组都被视为实
 * 现了 Cloneable 接口,并且 T[] 类型数组 clone 接口的返回类型是 T[],此处 T 可以
 * 是任意引用类型或原始类型。除此之外,此方法创建一个对象的类的新实例,然后用原本对象对
 * 应字段内容来初始化新实例所有字段,就像赋值;字段的内容不会被克隆。因此,此方法对对象
 * 执行了“浅拷贝”而不是一个“深拷贝”。
 * 
 * The class {@code Object} does not itself implement the interface
 * {@code Cloneable}, so calling the {@code clone} method on an object
 * whose class is {@code Object} will result in throwing an
 * exception at run time.
 * Object 类自身没有实现 Cloneable 接口,所以当对一个 Object 类的实例调用 clone 
 * 方法时将会在运行时抛出异常。
 * @return     a clone of this instance.
 * @throws  CloneNotSupportedException  if the object's class does not
 *               support the {@code Cloneable} interface. Subclasses
 *               that override the {@code clone} method can also
 *               throw this exception to indicate that an instance cannot
 *               be cloned.
 * @see java.lang.Cloneable
 */
protected native Object clone() throws CloneNotSupportedException;
复制代码
关注下面的标签,发现更多相似文章
评论