(三)从Object.clone()方法看浅拷贝和深拷贝

1.源码解析

protected native Object clone() throws CloneNotSupportedException;

创建并返回该对象的一个拷贝(Shallow-Copy),且这个“拷贝”的精确含义取决于该对象的类。如果该对象不支持Cloneable接口,则会抛出CloneNotSupportedException异常信息。
Object.clone()方法的通用约定如下:

对于任何对象x,表达式x.clone() != x返回true;
并且,表达式x.clone().getClass() == x.getClass()将会是true,但是这些都不是绝对的要求。
在通常情况下,表达式x.clone().equals(x)将会是true,但这也不是一个绝对的要求。

通用约定的解释:
按照惯例,应通过调用super.clone()方法获取返回的对象。如果一个类及其所有超类(Object除外)都遵守此约定,则x.clone().getClass()== x.getClass()就是这种情况。
按照惯例,super.clone()方法返回的对象应独立于源对象。为了实现这种独立性,可能有必要在返回之前修改super.clone()方法返回对象的一个​​或多个字段。通常,这意味着复制构成要克隆对象的内部“深度结构”的任何可变对象,并用对副本的引用替换对这些对象的引用。如果一个类仅包含基本字段或对不可变对象的引用,则通常情况下,无需修改super.clone()方法返回的对象中的任何字段。类Object的clone()方法执行特定的克隆操作。首先,如果此对象的类未实现接口Cloneable接口,则将引发CloneNotSupportedException。请注意,所有数组都被视为实现了接口Cloneable,数组类型为T []的clone方法的返回类型为T [],其中T为任何引用或原始类型。否则,此方法将创建此对象类的新实例,并使用该对象相应字段的内容完全初始化其所有字段,就像通过赋值一样;字段的内容本身不会被克隆。因此,此方法执行此对象的“浅拷贝”,而不是“深拷贝”操作。

2.通俗地讲一下浅拷贝和深拷贝
浅拷贝:创建并返回一个新对象,将当前对象的非static字段复制到该新对象。如果字段是基本类型,则复制该值;如果字段是引用类型,则复制引用。
如下图示例,类Employee拷贝一个新的Employee类对象,但共用一个Address类对象,但修改Address对象时,克隆的Employee类对象中的Address对象也会随之修改。

浅拷贝.png

深拷贝:创建并返回一个新对象,将当前对象的非static字段复制到该新对象。无论该字段是值类型还是引用类型,都复制独立的一份。当你修改其中一个对象的任何内容时,都不会影响到另一个对象的内容。


深拷贝.png

3.如何实现深拷贝
(1)实现Cloneable接口,让每个引用类型的内部属性都重写clone方法。

public class Student implements Cloneable{

    private int age;
    
    private String name;
    
    private Address address;
    
    public Student(int age, String name, Address address) {
        super();
        this.age = age;
        this.name = name;
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student [age=" + age + ", name=" + name + ", address=" + address + "]";
    }

    @Override
    protected Student clone() throws CloneNotSupportedException {
        Student student = (Student)super.clone();
        student.setAddress((Address) this.address.clone());
        return student;
    }
    
}
-------------------------------------------------------------------------------------------------------------------------------
public class Address implements Cloneable{

    private String province;

    private String city;

    private String county;
    
    public Address(String province, String city, String county) {
        super();
        this.province = province;
        this.city = city;
        this.county = county;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    @Override
    public String toString() {
        return "Address [province=" + province + ", city=" + city + ", county=" + county + "]";
    }

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

-------------------------------------------------------------------------------------------------------------------------------
public class StudentTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("广东省", "深圳市", "福田区");
        Student student = new Student(20,"Jack",address);
        
        // 调用clone()方法进行深拷贝
        Student studentCopy = student.clone();
        // 修改拷贝对象的值以测试是否影响源对象的值
        studentCopy.getAddress().setProvince("海南省");
        studentCopy.getAddress().setCity("海口市");
        studentCopy.getAddress().setCounty("龙华区");
        
        System.out.println("The student is:" + student);
        System.out.println("The studentCopy is:" + studentCopy);
        
    }
}
输出结果为:
The student is:Student [age=20, name=Jack, address=Address [province=广东省, city=深圳市, county=福田区]]
The studentCopy is:Student [age=20, name=Jack, address=Address [province=海南省, city=海口市, county=龙华区]]

从输出结果来看,让每个引用类型内部属性都重写clone方法可以实现对象深拷贝。

(2)利用序列化和反序列化的方式进行深度克隆对象

import java.io.Serializable;

public class Student implements Serializable,Cloneable{

    /**
     * 
     */
    private static final long serialVersionUID = -4037743305421493766L;

    private int age;
    
    private String name;
    
    private Address address;
    
    public Student(int age, String name, Address address) {
        super();
        this.age = age;
        this.name = name;
        this.address = address;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    @Override
    public String toString() {
        return "Student [age=" + age + ", name=" + name + ", address=" + address + "]";
    }

    @Override
    protected Student clone() throws CloneNotSupportedException {
        Student student = (Student)super.clone();
        student.setAddress((Address) this.address.clone());
        return student;
    }
    
}
-------------------------------------------------------------------------------------------------------------------------------
import java.io.Serializable;

public class Address implements Serializable,Cloneable{

    /**
     * 
     */
    private static final long serialVersionUID = -2704290616319012230L;

    private String province;

    private String city;

    private String county;
    
    public Address(String province, String city, String county) {
        super();
        this.province = province;
        this.city = city;
        this.county = county;
    }

    public String getProvince() {
        return province;
    }

    public void setProvince(String province) {
        this.province = province;
    }

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCounty() {
        return county;
    }

    public void setCounty(String county) {
        this.county = county;
    }

    @Override
    public String toString() {
        return "Address [province=" + province + ", city=" + city + ", county=" + county + "]";
    }

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

-------------------------------------------------------------------------------------------------------------------------------
import org.apache.commons.lang3.SerializationUtils;

/**
 * @author Davince
 */
public class StudentTest {

    public static void main(String[] args) throws CloneNotSupportedException {
        Address address = new Address("广东省", "深圳市", "福田区");
        Student student = new Student(20,"Jack",address);
        
        // 调用clone()方法进行深拷贝
        Student studentCopy = student.clone();
        // 修改拷贝对象的值以测试是否影响源对象的值
        studentCopy.getAddress().setProvince("海南省");
        studentCopy.getAddress().setCity("海口市");
        studentCopy.getAddress().setCounty("龙华区");
        
        System.out.println("The student is:" + student);
        System.out.println("The studentCopy is:" + studentCopy);
        
        Address address2 = new Address("广东省", "广州市", "珠江新区");
        Student student2 = new Student(20,"Rose",address2);
        
        // 使用ApacheCommonsLang包序列化进行深拷贝
        Student studentSerialization = SerializationUtils.clone(student2);
        // 修改拷贝对象的值以测试是否影响源对象的值
        studentSerialization.getAddress().setProvince("海南省");
        studentSerialization.getAddress().setCity("三亚市");
        studentSerialization.getAddress().setCounty("解放路");
        
        System.out.println("The student2 is:" + student2);
        System.out.println("The studentSerialization is:" + studentSerialization);
        
    }
}
输出结果为:
The student is:Student [age=20, name=Jack, address=Address [province=广东省, city=深圳市, county=福田区]]
The studentCopy is:Student [age=20, name=Jack, address=Address [province=海南省, city=海口市, county=龙华区]]
The student2 is:Student [age=20, name=Rose, address=Address [province=广东省, city=广州市, county=珠江新区]]
The studentSerialization is:Student [age=20, name=Rose, address=Address [province=海南省, city=三亚市, county=解放路]]

从输出结果来看,让每个引用类型内部属性都重写clone方法和Java序列化反序列化的方法都可以实现对象深拷贝。

SerializationUtils工具类源码解析:封装了Java原生的序列化与反序列化,性能一般,可作为学习参考使用。

package org.apache.commons.lang3;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.ObjectStreamClass;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Assists with the serialization process and performs additional functionality based
 * on serialization.</p>
 *
 * <ul>
 * <li>Deep clone using serialization
 * <li>Serialize managing finally and IOException
 * <li>Deserialize managing finally and IOException
 * </ul>
 *
 * <p>This class throws exceptions for invalid {@code null} inputs.
 * Each method documents its behaviour in more detail.</p>
 *
 * <p>#ThreadSafe#</p>
 * @since 1.0
 */
public class SerializationUtils {

    /**
     * <p>SerializationUtils instances should NOT be constructed in standard programming.
     * Instead, the class should be used as {@code SerializationUtils.clone(object)}.</p>
     *
     * <p>This constructor is public to permit tools that require a JavaBean instance
     * to operate.</p>
     * @since 2.0
     */
    public SerializationUtils() {
        super();
    }

    // Clone
    //-----------------------------------------------------------------------
    /**
     * <p>Deep clone an {@code Object} using serialization.</p>
     *
     * <p>This is many times slower than writing clone methods by hand
     * on all objects in your object graph. However, for complex object
     * graphs, or for those that don't support deep cloning this can
     * be a simple alternative implementation. Of course all the objects
     * must be {@code Serializable}.</p>
     *
     * @param <T> the type of the object involved
     * @param object  the {@code Serializable} object to clone
     * @return the cloned object
     * @throws SerializationException (runtime) if the serialization fails
     */
    public static <T extends Serializable> T clone(final T object) {
        if (object == null) {
            return null;
        }
        final byte[] objectData = serialize(object);
        final ByteArrayInputStream bais = new ByteArrayInputStream(objectData);

        try (ClassLoaderAwareObjectInputStream in = new ClassLoaderAwareObjectInputStream(bais,
                object.getClass().getClassLoader())) {
            /*
             * when we serialize and deserialize an object,
             * it is reasonable to assume the deserialized object
             * is of the same type as the original serialized object
             */
            @SuppressWarnings("unchecked") // see above
            final T readObject = (T) in.readObject();
            return readObject;

        } catch (final ClassNotFoundException ex) {
            throw new SerializationException("ClassNotFoundException while reading cloned object data", ex);
        } catch (final IOException ex) {
            throw new SerializationException("IOException while reading or closing cloned object data", ex);
        }
    }

    /**
     * Performs a serialization roundtrip. Serializes and deserializes the given object, great for testing objects that
     * implement {@link Serializable}.
     *
     * @param <T>
     *           the type of the object involved
     * @param msg
     *            the object to roundtrip
     * @return the serialized and deserialized object
     * @since 3.3
     */
    @SuppressWarnings("unchecked") // OK, because we serialized a type `T`
    public static <T extends Serializable> T roundtrip(final T msg) {
        return (T) deserialize(serialize(msg));
    }

    // Serialize
    //-----------------------------------------------------------------------
    /**
     * <p>Serializes an {@code Object} to the specified stream.</p>
     *
     * <p>The stream will be closed once the object is written.
     * This avoids the need for a finally clause, and maybe also exception
     * handling, in the application code.</p>
     *
     * <p>The stream passed in is not buffered internally within this method.
     * This is the responsibility of your application if desired.</p>
     *
     * @param obj  the object to serialize to bytes, may be null
     * @param outputStream  the stream to write to, must not be null
     * @throws IllegalArgumentException if {@code outputStream} is {@code null}
     * @throws SerializationException (runtime) if the serialization fails
     */
    public static void serialize(final Serializable obj, final OutputStream outputStream) {
        Validate.isTrue(outputStream != null, "The OutputStream must not be null");
        try (ObjectOutputStream out = new ObjectOutputStream(outputStream)) {
            out.writeObject(obj);
        } catch (final IOException ex) {
            throw new SerializationException(ex);
        }
    }

    /**
     * <p>Serializes an {@code Object} to a byte array for
     * storage/serialization.</p>
     *
     * @param obj  the object to serialize to bytes
     * @return a byte[] with the converted Serializable
     * @throws SerializationException (runtime) if the serialization fails
     */
    public static byte[] serialize(final Serializable obj) {
        final ByteArrayOutputStream baos = new ByteArrayOutputStream(512);
        serialize(obj, baos);
        return baos.toByteArray();
    }

    // Deserialize
    //-----------------------------------------------------------------------
    /**
     * <p>
     * Deserializes an {@code Object} from the specified stream.
     * </p>
     *
     * <p>
     * The stream will be closed once the object is written. This avoids the need for a finally clause, and maybe also
     * exception handling, in the application code.
     * </p>
     *
     * <p>
     * The stream passed in is not buffered internally within this method. This is the responsibility of your
     * application if desired.
     * </p>
     *
     * <p>
     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
     * Note that in both cases, the ClassCastException is in the call site, not in this method.
     * </p>
     *
     * @param <T>  the object type to be deserialized
     * @param inputStream
     *            the serialized object input stream, must not be null
     * @return the deserialized object
     * @throws IllegalArgumentException
     *             if {@code inputStream} is {@code null}
     * @throws SerializationException
     *             (runtime) if the serialization fails
     */
    public static <T> T deserialize(final InputStream inputStream) {
        Validate.isTrue(inputStream != null, "The InputStream must not be null");
        try (ObjectInputStream in = new ObjectInputStream(inputStream)) {
            @SuppressWarnings("unchecked")
            final T obj = (T) in.readObject();
            return obj;
        } catch (final ClassNotFoundException | IOException ex) {
            throw new SerializationException(ex);
        }
    }

    /**
     * <p>
     * Deserializes a single {@code Object} from an array of bytes.
     * </p>
     *
     * <p>
     * If the call site incorrectly types the return value, a {@link ClassCastException} is thrown from the call site.
     * Without Generics in this declaration, the call site must type cast and can cause the same ClassCastException.
     * Note that in both cases, the ClassCastException is in the call site, not in this method.
     * </p>
     *
     * @param <T>  the object type to be deserialized
     * @param objectData
     *            the serialized object, must not be null
     * @return the deserialized object
     * @throws IllegalArgumentException
     *             if {@code objectData} is {@code null}
     * @throws SerializationException
     *             (runtime) if the serialization fails
     */
    public static <T> T deserialize(final byte[] objectData) {
        Validate.isTrue(objectData != null, "The byte[] must not be null");
        return deserialize(new ByteArrayInputStream(objectData));
    }

    /**
     * <p>Custom specialization of the standard JDK {@link java.io.ObjectInputStream}
     * that uses a custom  <code>ClassLoader</code> to resolve a class.
     * If the specified <code>ClassLoader</code> is not able to resolve the class,
     * the context classloader of the current thread will be used.
     * This way, the standard deserialization work also in web-application
     * containers and application servers, no matter in which of the
     * <code>ClassLoader</code> the particular class that encapsulates
     * serialization/deserialization lives. </p>
     *
     * <p>For more in-depth information about the problem for which this
     * class here is a workaround, see the JIRA issue LANG-626. </p>
     */
     static class ClassLoaderAwareObjectInputStream extends ObjectInputStream {
        private static final Map<String, Class<?>> primitiveTypes =
                new HashMap<>();

        static {
            primitiveTypes.put("byte", byte.class);
            primitiveTypes.put("short", short.class);
            primitiveTypes.put("int", int.class);
            primitiveTypes.put("long", long.class);
            primitiveTypes.put("float", float.class);
            primitiveTypes.put("double", double.class);
            primitiveTypes.put("boolean", boolean.class);
            primitiveTypes.put("char", char.class);
            primitiveTypes.put("void", void.class);
        }

        private final ClassLoader classLoader;

        /**
         * Constructor.
         * @param in The <code>InputStream</code>.
         * @param classLoader classloader to use
         * @throws IOException if an I/O error occurs while reading stream header.
         * @see java.io.ObjectInputStream
         */
        ClassLoaderAwareObjectInputStream(final InputStream in, final ClassLoader classLoader) throws IOException {
            super(in);
            this.classLoader = classLoader;
        }

        /**
         * Overridden version that uses the parameterized <code>ClassLoader</code> or the <code>ClassLoader</code>
         * of the current <code>Thread</code> to resolve the class.
         * @param desc An instance of class <code>ObjectStreamClass</code>.
         * @return A <code>Class</code> object corresponding to <code>desc</code>.
         * @throws IOException Any of the usual Input/Output exceptions.
         * @throws ClassNotFoundException If class of a serialized object cannot be found.
         */
        @Override
        protected Class<?> resolveClass(final ObjectStreamClass desc) throws IOException, ClassNotFoundException {
            final String name = desc.getName();
            try {
                return Class.forName(name, false, classLoader);
            } catch (final ClassNotFoundException ex) {
                try {
                    return Class.forName(name, false, Thread.currentThread().getContextClassLoader());
                } catch (final ClassNotFoundException cnfe) {
                    final Class<?> cls = primitiveTypes.get(name);
                    if (cls != null) {
                        return cls;
                    }
                    throw cnfe;
                }
            }
        }

    }

}

原创不易,如需转载,请注明出处@author Davince!

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 204,590评论 6 478
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 86,808评论 2 381
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 151,151评论 0 337
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,779评论 1 277
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,773评论 5 367
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,656评论 1 281
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 38,022评论 3 398
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,678评论 0 258
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 41,038评论 1 299
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,659评论 2 321
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,756评论 1 330
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,411评论 4 321
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 39,005评论 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,973评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,203评论 1 260
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 45,053评论 2 350
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,495评论 2 343

推荐阅读更多精彩内容