【命运只会眷顾努力的人】手把手用实例教你实现java中的克隆,再不会就过分了!

 
生命不息,奋斗不止!(送给也曾迷茫的你)

 


1. Java中的克隆

克隆 (Clone)就是进行复制,Java语言中克隆针对的是类的实例,复制引用类型的对象。通过调用clone方法对引用类型和对象来实现克隆。如果是值类型的实例,“=”赋值运算符就可以将源对象的状态逐字节地复制到目标对象中。

  • Cloneable.class 源码
    通过阅读Cloneable接口的注释,可以得知Java实现克隆需要遵循以下规则:
    1.必须实现Cloneable接口(一个没有抽象方法的标识接口);
    2.实现Cloneable的类应该重写clone(),且重写时该方法的修饰符为public。
/*
 * Copyright (c) 1995, 2004, Oracle and/or its affiliates. All rights reserved.
 * ORACLE PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
 */

package java.lang;

/**
 * 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.
 * (一个类实现了Cloneable接口意味着可以通过java.lang.Object的clone()方法合法的对该类的实例进行字段对字段的复制。)
 * <p>
 * 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.
 * (对一个没有实现Cloneable接口的类的实例,调用clone()会抛出CloneNotSupportedException异常。)
 * <p>
 * By convention, classes that implement this interface should override
 * {@code Object.clone} (which is protected) with a public method.
 * See {@link java.lang.Object#clone()} for details on overriding this
 * method.
 * (按照惯例,实现了此接口的类应该重写clone(),重写时将该方法由受保护变为公开。)
 * <p>
 * Note that this interface does <i>not</i> contain the {@code clone} 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()。因此,仅依靠实现此接口是不可能实现对象克隆的。即使clone()被成功调用,也不能保证克隆可以成功。)
 *
 * @author  unascribed
 * @see     java.lang.CloneNotSupportedException
 * @see     java.lang.Object#clone()
 * @since   1.0
 */
public interface Cloneable {
}

 

  • 克隆调用的Object类的clone()方法源码
    克隆调用的是Object类的clone()方法,clone()是一个本地方法,默认的修饰符是protected。
    本地方法是由其它语言(c或者C++)编写的,编译成和处理器相关的机器代码。本地方法保存在动态链接库中,即.dll(windows系统)文件中,格式是各个平台专有的。虚拟机装载包含这个本地方法的动态库,并调用这个方法,通过本地方法,JAVA程序可以直接访问底层操作系统的资源。

    查看本地方法 → OpenJDK
    /**
     * 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:
     * (创建并返回该对象的副本,“copy”的确切含义可能取决于对象的类。)
     * <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>
     * 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>
     * 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>
     * 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.
     * (注意,所有数组被认为是实现了 Cloneable接口的,clone方法返回一个泛型数组。)
     * 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.
     * (clone方法将创建这个类的新实例对象并初始化它的所有字段,但字段本身没有被克隆。因此这种方法对该对象执行的是“浅拷贝”,而不是“深拷贝”操作。)
     * <p>
     * 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.
     * (类本身并不实现接口,因此在对象上调用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
     */
    @HotSpotIntrinsicCandidate
    protected native Object clone() throws CloneNotSupportedException;

 


2. 为什么要克隆对象

  1. 想对一个对象进行处理,又想保留原有的数据进行接下来的操作。
  2. 基于现有对象创建略有不同的版本。
  3. 制作对象的防御性副本,无论消费者如何处理数据,保证原始对象都是安全的,不会受到影响。
  4. 速度快,克隆不会调用构造方法,创建新的实例会调用构造方法而且还是初始化时候的值。

 


3. 使用clone()实现浅克隆

浅克隆:创建一个新对象,新对象的属性和原来对象完全相同,对于非基本类型属性,仍指向原有属性所指向的对象的内存地址。

*****************************************************************
package com.it.god.controller;

public class CloneController {

    public static void main(String[] args) throws CloneNotSupportedException {

        Teacher teacher = new Teacher("白羊", 27);
        Student stu1 = new Student("吴峥", 26, teacher);
        Student stu2 = stu1.clone();
        System.out.println(stu1.getName() + stu2.getAge() + stu2.getTeacher().getName());
        // 对学生一的老师进行更改
        teacher.setName("ouseki");
        // 克隆对象学生二的老师也随之改变
        System.out.println(stu1.getName() + stu2.getAge() + stu2.getTeacher().getName());

    }

}

class Student implements Cloneable {
    private String name;
    private int age;
    private Teacher teacher;

    @Override
    public Student clone() throws CloneNotSupportedException {
        Student student = (Student) super.clone();
        // 手动实现深克隆(一会进行深克隆的时候放开注释即可)
        // student.setTeacher(student.getTeacher().clone());
        return student;
    }

	// 省略set、get方法以及构造器

}

class Teacher implements Cloneable {
    private String name;
    private int age;

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

	// 省略set、get方法以及构造器
}
-----------------------------------------------------------------
・【运行结果】
	吴峥26白羊
	吴峥26ouseki
*****************************************************************

 


4. 使用clone()实现深克隆

深克隆:创建一个新对象,属性中引用的其他对象也会被克隆,不再指向原有对象地址。
缺点:每一层对象对应的类都必须支持深克隆,需要为每一个类都配置一个 clone 方法。

*****************************************************************
package com.it.god.controller;

public class CloneController {

    public static void main(String[] args) throws CloneNotSupportedException {

        Teacher teacher = new Teacher("白羊", 27);
        Student stu1 = new Student("吴峥", 26, teacher);
        Student stu2 = stu1.clone();
        System.out.println(stu1.getName() + stu2.getAge() + stu2.getTeacher().getName());
        // 对学生一的老师进行更改
        teacher.setName("ouseki");
        // 克隆对象学生二的老师不会改变
        System.out.println(stu1.getName() + stu2.getAge() + stu2.getTeacher().getName());

    }

}

class Student implements Cloneable {
    private String name;
    private int age;
    private Teacher teacher;

    @Override
    public Student clone() throws CloneNotSupportedException {
        Student student = (Student) super.clone();
        // 手动实现深克隆
        student.setTeacher(student.getTeacher().clone());
        return student;
    }

	// 省略set、get方法以及构造器

}

class Teacher implements Cloneable {
    private String name;
    private int age;

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

	// 省略set、get方法以及构造器
}
-----------------------------------------------------------------
・【运行结果】
	吴峥26白羊
	吴峥26白羊
*****************************************************************

 


5. 使用序列化反序列化实现深克隆

缺点:对象图中的所有类都需要实现Serializable,对象的瞬态属性不能克隆。

不懂什么是瞬态 → 点击这里

*****************************************************************
package com.it.god.controller;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class CloneController {

    public static void main(String[] args) throws CloneNotSupportedException {

        Teacher teacher = new Teacher("白羊", 27);
        Student stu1 = new Student("吴峥", 26, teacher);
        Student stu2 = null;
        try {
            stu2 = stu1.deepClone();
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        System.out.println(stu1.getName() + stu2.getAge() + stu2.getTeacher().getName());
        teacher.setName("ouseki");
        System.out.println(stu1.getName() + stu2.getAge() + stu2.getTeacher().getName());

    }

}
class Student implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;
    private Teacher teacher;

    public Student deepClone() throws IOException, ClassNotFoundException {
        // 将当前这个对象写到一个输出流当中,,如果这个对象的引用类也实现了Serializable这个接口,那么这个类也会写到输出流中
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(this);

        // 将流中的东西读出来,返回这两个对象的东西,实现深克隆
        ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
        ObjectInputStream ois = new ObjectInputStream(bis);
        return (Student) ois.readObject();
    }

	// 省略set、get方法以及构造器

}

class Teacher implements Serializable {
    private static final long serialVersionUID = 1L;
    private String name;
    private int age;

	// 省略set、get方法以及构造器
	
}
-----------------------------------------------------------------
・【运行结果】
	吴峥26白羊
	吴峥26白羊
*****************************************************************
  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值