原文地址:http://leihuang.org/2014/11/14/java-clone/

In java, it essentially means the ability to create an object with similar state as the original object.

什么是clone

字典中的意思就是复制(强调跟原来的一模一样)。

*By default, java cloning is ‘field by field copy’ *.由于Object类不知道详细类的结构,无法确定哪个clone方法将被调用。

所以JVM规定clone,做例如以下操作。

  1. 假设这个类仅仅有原始数据类型成员的话。那么须要创建一个一模一样的对象,而且返回这个新对象的引用。
  2. 假设这个类包括了不论什么类类型成员的话,那么仅仅有这些成员的对象引用被复制。且原始对象和克隆对象的成员的引用将指向同一个对象。

翻译的不好。%>_<%

  1. If the class has only primitive data type members then a completely new copy of the object will be created and the reference to the new object copy will be returned.
  2. If the class contains members of any class type then only the object references to those members are copied and hence the member references in both the original object as well as the cloned object refer to the same object.

除了上面两条默认的操作之外。你也能够重载clone方法,制定一套自己的clone方法。


java中clone规则

每种支持clone的语言都有它自己的规则,java也不例外。java中假设一个类需要支持clone的话。必需要做例如以下事情:

  1. 你必须继承Cloneable接口---Cloneable interface is broken in java。otherwise throws java.lang.CloneNotSupportedException.
  2. 必须重写Object类中的clone()方法
/*
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 x, the expression:
1) x.clone() != x will be true
2) x.clone().getClass() == x.getClass() will be true, but these are not absolute requirements.
3) x.clone().equals(x) will be true, this is not an absolute requirement.
*/
protected native Object [More ...] clone() throws CloneNotSupportedException;

  1. 第一条表明,clone对象分配有独立的内存地址。
  2. 第二条表明,原始的和克隆的对象应该具有同样类型,但这不是必须的
  3. 第三条表明。原始的和克隆的对象调用equals方法的话,应该时相等的。但这不是必须的。

以下我们通过样例来分析:

class Father implements Cloneable{
private int age ;
private String name ;
private Son son ; public Father(int age,String name,Son son){
this.age = age ;
this.name = name ;
this.son = son ;
} public Son getSon(){
return this.son ;
} @Override
protected Object clone()throws CloneNotSupportedException{
return super.clone() ;
}
}
class Son{
private int age ;
private String name ; public Son(int age ,String name){
this.age = age ;
this.name = name ;
} public void setName(String name){
this.name = name ;
}
public String getName(){
return this.name ;
}
}
public class CloneDemo {
public static void main(String args[]) throws CloneNotSupportedException{
Son s = new Son(10,"Jack") ;
Father fa = new Father(40,"Tom",s) ;
Father clonedFa = (Father) fa.clone() ; System.out.println(fa!=clonedFa);
System.out.println(clonedFa.getClass()==fa.getClass());
System.out.println(clonedFa.equals(fa)); //now we change the fa's son name by the clonedFa's son name
clonedFa.getSon().setName("Jay");
System.out.println(fa.getSon().getName());
}
}
/*print:
true
true
false
Jay
*/

上面的代码中能够看出。原始的和克隆的Father类对象。拥有指向同一对象的两个引用。所以能够通过改变clonedFa中的Son来改变fa中Son对象。这就时所谓的浅拷贝.以下我们具体讨论一下浅拷贝和深拷贝。

浅拷贝(Shallow Cloning)

这是java中默认的实现。上面的样例中就是浅拷贝。不创建一个新的克隆拷贝对象Son,而是直接两个引用指向同一对象。

深拷贝

If we want a clone which is independent of original and making changes in clone should not affect original.you can try Deep Cloning.

we change the clone() method in the Father class .

@Override
protected Object clone() throws CloneNotSupportedException {
Father fa = (Father)super.clone();
fa.setSon((Son)fa.getSon().clone());
return fa;
}

and we need Override the clone() method in the Son class. like this.

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

如今我们已经实现深拷贝了。

拷贝构造函数

拷贝构造函数时一种特殊的构造器。它讲自己的类类型作为參数。我们传递一个类的实例给拷贝构造函数。然后它将返回一个新的类实例。lets see this in example

public class PointOne {
private Integer x;
private Integer y; public PointOne(PointOne point){
this.x = point.x;
this.y = point.y;
}
}

假设要继承它的话,则须要复制子类的參数,和传递參数给父类的构造器。

例如以下:

public class PointTwo extends PointOne{
private Integer z; public PointTwo(PointTwo point){
super(point); //Call Super class constructor here
this.z = point.z;
}
}

以下是測试代码:

class Test
{
public static void main(String[] args)
{
PointOne one = new PointOne(1,2);
PointTwo two = new PointTwo(1,2,3); PointOne clone1 = new PointOne(one);
PointOne clone2 = new PointOne(two); //Let check for class types
System.out.println(clone1.getClass());
System.out.println(clone2.getClass());
}
}
Output:
class corejava.cloning.PointOne
class corejava.cloning.PointOne

你也能够使用静态工厂的方法来实现它。

public class PointOne {
private Integer x;
private Integer y; public PointOne(Integer x, Integer y)
{
this.x = x;
this.y = y;
} public PointOne copyPoint(PointOne point) throws CloneNotSupportedException
{
if(!(point instanceof Cloneable))
{
throw new CloneNotSupportedException("Invalid cloning");
}
//Can do multiple other things here
return new PointOne(point.x, point.y);
}
}

Cloning with serialization

这是例外一种深拷贝的方法。这里就不多讲了,具体见:A mini guide for implementing serializable interface in java

best practices

1) When you don’t know whether you can call the clone() method of a particular class as you are not sure if it is implemented in that class, you can check with checking if the class is instance of “Cloneable” interface as below.

if(obj1 instanceof Cloneable){
obj2 = obj1.clone();
}
//Dont do this. Cloneabe dont have any methods
obj2 = (Cloneable)obj1.clone();

2) No constructor is called on the object being cloned. As a result, it is your responsibility, to make sure all the members have been properly set. Also, if you are keeping track of number of objects in system by counting the invocation of constructors, you
got a new additional place to increment the counter.

Reference:

  1. A guide to object cloning in java
  2. Effective--Java Item 11: Override clone judiciously(讲的更具体,各种clone方式的优缺点都讲了)

2014-11-14 15:48:12

Brave,Happy,Thanksgiving !

版权声明:本文博主原创文章。博客,未经同意不得转载。

j详细说明ava于clone办法的更多相关文章

  1. 使用 IntelliJ IDEA 2016和Maven创建Java Web项目的详细步骤及相关问题解决办法

    Maven简介 相对于传统的项目,Maven 下管理和构建的项目真的非常好用和简单,所以这里也强调下,尽量使用此类工具进行项目构建, 它可以管理项目的整个生命周期. 可以通过其命令做所有相关的工作,其 ...

  2. jquery的clone办法bug修复

    发现测试,textarea和select的jquery的clone有问题的方法,textarea和select值clone时间会输.这是发现jquery一个bug,上不了的能够看下代码.比較简单.就是 ...

  3. j疑难杂症:ava.lang.NoSuchMethodError: com.opensymphony.xwork2.util.finder.ClassFinder.<init>

    严重: Exception starting filter struts2java.lang.NoSuchMethodError: com.opensymphony.xwork2.util.finde ...

  4. j经常使用ava应用server

    什么是应用server它?它主要提供的执行环境的应用程序,为组件提供服务. 要了解更多关于,您可以查看我的博客:何为容器? Java 的应用server非常多,从功能上分为两类:WEB 应用serve ...

  5. Linux 查找指定名称的进程并显示进程详细信息

    实际应用中可能有这样的场景:给定一个进程名称特征串,查找所有匹配该进程名称的进程的详细信息. 解决的办法是: (1) 先用pgrep [str] 命令进行模糊匹配,找到匹配该特征串的进程ID: (2) ...

  6. Mysql 死锁的详细分析方法

    用数据库的时候,偶尔会出现死锁,针对我们的业务系统,出现死锁的直接结果就是系统卡顿.客户找事儿,所以我们也在想尽全力的消除掉数据库的死锁.出现死锁的时候,如果只是想解锁,用show full proc ...

  7. [C#] .NET Core项目修改project.json来引用其他目录下的源码等文件的办法 & 解决多框架时 project.json 与 app.config冲突的问题

    作者: zyl910 一.缘由 项目规模大了后,经常会出现源码文件分布在不同目录的情况,但.NET Core项目默认只有项目目录下的源码文件,且不支持"Add As Link"方式 ...

  8. java对象的深浅clone

    在Java语言中,数据类型分为值类型(基本数据类型)和引用类型,值类型包括int.double.byte.boolean.char等简单数据类型,引用类型包括类.接口.数组等复杂类型. 浅克隆和深克隆 ...

  9. .NET Core项目修改project.json来引用其他目录下的源码等文件的办法 & 解决多框架时 project.json 与 app.config冲突的问题

    作者: zyl910 一.缘由 项目规模大了后,经常会出现源码文件分布在不同目录的情况,但.NET Core项目默认只有项目目录下的源码文件,且不支持“Add As Link”方式引入文件.这时需要手 ...

随机推荐

  1. C 中注意的小问题

    输入:char ch[100],gets(ch); scanf("%d",&in); char ch,ch=getchar(); VC:  所有变量声明放在所有操作前面: ...

  2. selenium webdriver 学习笔记(一)

    selenium webdriver 第一个脚本: #coding = utf-8 from selenium import webdriver import time url = "htt ...

  3. JS中String的反转函数

    利用prototype封住reverse方法: (求更简便的方法: String.prototype.reverse=function () { var str=""; for(v ...

  4. C#的线程池的那些事

    最近在做站时发现,线程池的问题很棘手,所以总结了一篇关于线程池的文章,原文地址:http://www.shuonar.com/blog/ac16496b-87ec-4790-a9ea-d69bbffa ...

  5. 服务没有mysql

    你安装了mysql没有,没有就先安装,安装好mysql以后,在bin目录下有个mysqld.exe,运行这个程序就可以添加mysql服务,但是运行这个程序需要使用参数,否则就会以命令行窗口形式启动MY ...

  6. Sprite Kit编程指南中文版下载

    下载地址:http://download.csdn.net/detail/xin814/6032573 关于Sprite Kit 重要提示:  这是API或开发技术的一个初版文档.虽然本文档的技术准确 ...

  7. c#搭建服务端 准备工作(1)

    思路 搭建服务器主要为了接收客户端所传来的数据,在学习过程中,整体的搭建逻辑大体分为以下几个步骤: 1.启动线程监听服务端口 2.监听客户端链接并进行处理 3.接收客户端传入的消息 4.向客户端回传( ...

  8. swift3.0 扩展、协议(4)

    扩展和协议是swift中的两个特性,用于对已有的类型进行扩展和修改. 扩展(extension) 向已经存在的类型添加新的功能(属性.方法.下标脚本等等),扩展使用extension关键字定义,语法 ...

  9. Unity3D游戏开发从零单排(五) - 导入CS模型到Unity3D

    游戏动画基础 Animation组件 Animation组件是对于老的动画系统来说的. 老的动画形同相应的动画就是clip,每一个运动都是一段单独的动画,使用Play()或CrossFade(),直接 ...

  10. Ceph对象存储网关中的索引工作原理<转>

    Ceph 对象存储网关允许你通过 Swift 及 S3 API 访问 Ceph .它将这些 API 请求转化为 librados 请求.Librados 是一个非常出色的对象存储(库)但是它无法高效的 ...