Object对象具体解释(二)之clone
clone方法会返回该实例对象的一个副本,通常情况下x.clone() != x || x.clone().getClass() == x.getClass() || x.clone().equals(x)也为真。但不严格要求,我们能够通过重写该方法来覆盖。
protected native Object clone() throws CloneNotSupportedException;
能够看到。clone是一个本地方法,可能会抛出CloneNotSupportedException异常,什么情况下会抛出呢?
/**
* 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>
* 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>
* 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.
* <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.
*
* @author unascribed
* @see java.lang.CloneNotSupportedException
* @see java.lang.Object#clone()
* @since JDK1.0
*/
public interface Cloneable {
}
说明中写到。假设该对象未实现Cloneable 接口。那么当实例调用clone方法时。就会抛出该异常。
以下看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 {@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>
* 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.
* 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>
* 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.
*
* @return a clone of this instance.
* @exception 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;
当中提到的重写clone方法的几个注意点
1. 数组视为自己主动实现了Cloneable接口;
2. 非数组类型,使用clone方法,须要实现Cloneable接口。否则会抛出异常;
3. 非数组类型,克隆时,会新创建一个该类型的实例,并将被克隆对象实例的状态复制给新创建对象。而且这是一个浅克隆-(影子克隆——shallow copy),而不是deep copy;
4. 重写clone方法时。首先首先首先须要调用父类的clone方法。
那么问题来了。什么是shallow copy?而deep copy又是什么?
上样例:
public class Test {
public static void main(String[] args) throws CloneNotSupportedException {
People people = new People("zjh", '男', 21, new Cloth(COLOR.WHITE , "XXL"));
People clone = (People) people.clone();
System.out.println("people == clone : " + (people == clone));
System.out.println("people.getCloth() == clone.getCloth() : "+ (people.getCloth() == clone.getCloth()));
System.out.println("people.getAge() == clone.getAge() : "+(people.getAge() == clone.getAge()));
System.out.println("people.getName() == clone.getName() : "+(people.getName() == clone.getName()));
}
}
class People implements Cloneable{
private String name;
private char sex;
private int age;
private Cloth cloth;
/**
* {@inheritDoc}.
*/
@Override
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
return super.clone();
}
...若干getter/setter方法
}
class Cloth{
private COLOR color;
private String size;
/**
* 构造函数.
*
* @param color
* @param size
*/
public Cloth(COLOR color, String size) {
super();
this.color = color;
this.size = size;
}
enum COLOR {
RED,WHITE,BLACK,GREEN,BLUE
}
}
执行结果:
people == clone : false
people.getCloth() == clone.getCloth() : true
people.getSex() == clone.getSex() : true
people.getName() == clone.getName() : true
age,sex。name比較为真还能理解,为什么people.getCloth() == clone.getCloth() 也是true呢?又做了以下的測试。
people.getCloth().setColor(COLOR.BLACK);
System.out.println(clone.getCloth().getColor());
执行结果:
BLACK
如今已经能确定,people和它的克隆对象clone中的cloth引用指向了同一个Cloth实例。这就是“shallow copy”。那么想要“deep copy”。那么就须要在重写方法的时候,同一时候调用对象属性的克隆方法(要求该属性对象也须要实现Cloneable)。
clone方法改动例如以下:
protected Object clone() throws CloneNotSupportedException {
// TODO Auto-generated method stub
People clone = (People) super.clone();
clone.setCloth((Cloth)cloth.clone());
return clone;
}
再执行上面的測试程序:
people == clone : false
people.getCloth() == clone.getCloth() : false
people.getAge() == clone.getAge() : true
people.getSex() == clone.getSex() : true
people.getName() == clone.getName() : true
Object对象具体解释(二)之clone的更多相关文章
- Object对象具体解释(一)之toString
Object作为Java中超然的存在.当中定义了一切对象都共同拥有的方法. 特点: 1. java.lang包在使用的时候无需显示导入.编译时由编译器自己主动导入. 2. Object类是类层次结构的 ...
- Android 消息传递之Bundle的使用——实现object对象传输(二)
上面学习了线程通过Massage发送字符串消息,Handler接收字符串消息,这样的形式来更新ui,接下来,一起分享怎么把一个对象利用消息机制发送出去,让主线程接收来更新ui. 下面就利用一个服务Se ...
- java Object对象的clone方法
参考copy链接:http://blog.csdn.net/bigconvience/article/details/25025561 在看原型模式,发现要用到clone这个方法,以前和朋友聊过,没怎 ...
- Scala学习教程笔记二之函数式编程、Object对象、伴生对象、继承、Trait、
1:Scala之函数式编程学习笔记: :Scala函数式编程学习: 1.1:Scala定义一个简单的类,包含field以及方法,创建类的对象,并且调用其方法: class User { private ...
- js object对象赋值bug和对象复制clone方法
最近在写程序的时候发现,如果新建一个object对象objb,初始化值为obja,如果改变了objb对象的字段值,那么obja也会随之改变,看来对象赋值传递的是一个引用. 代码重现: <scri ...
- Object对象你真理解了吗?
前言 五一回家又断更了一个放假时间了~~~ 只有光头才能变强 回顾前面: ThreadLocal就是这么简单 多线程三分钟就可以入个门了! 多线程基础必要知识点!看了学习多线程事半功倍 Java锁机制 ...
- Java:Object对象小记
Java:Object对象小记 对 Java 中的 Object 对象,做一个微不足道的小小小小记 Object 的常用方法有哪些 clone() 方法:用于创建并返回当前对象的一份拷贝: 在Java ...
- Intent.putExtra()传递Object对象或者ArrayList<Object> (转)
Intent传递基本类型相信大家都十分熟悉,如何传递Object对象或者ArrayList<Object>对象呢? 可以通过: (1)public Intent putExtra (Str ...
- javascript ES5 Object对象
原文:http://javascript.ruanyifeng.com/stdlib/object.html 目录 概述 Object对象的方法 Object() Object.keys(),Obje ...
随机推荐
- go之switch
switch 条件语句一 格式 switch initialization{ case v1: // do something case v2: // do something case v2: // ...
- B - Sleuth
Problem description Vasya plays the sleuth with his friends. The rules of the game are as follows: t ...
- Oracle 关于oracle自带的行转列函数
前言: 环境是java+hibernate+oracle11g 目标是将某表中根据id分组后将name字段的值拼接到一列中,且用“,“进行分割 试过用 wm_concat() 结合 group by ...
- Spring logger 配置
1. logback-spring.xml <?xml version="1.0" encoding="UTF-8"?> <configura ...
- 八:前端---Vue下的国际化处理
1:首先安装 Vue-i8n npm install vue-i18n --save 注:-save-dev是指将包信息添加到devDependencies,表示你开发时依赖的包裹. -save是指将 ...
- 算法之dfs篇
dfs算法是深度搜索算法.从某一节点开始遍历直至到路径底部,如果不是所寻找的,则回溯到上个节点后,再遍历其他路径.不断重复这个过程.一般此过程消耗很大,需要一些优化才能保持算法的高效. hdu1010 ...
- ★Java-----记事本编译、运行时注意事项
1.文件名需要与源代码中公共类的名字相同,即class后面的名字: 2.Java中严格区分大小写: 3.记事本编辑好之后保存文件后缀必须是". java": 4.运行cmd,dos ...
- JAVA 构建使用 Native 库
Java 使用Native文件,一般分解为下面几个步骤: 在Java代码中使用native关键字声明一个本地方法 运行javah,获得包含该方法声明的C语言头文件(使用jni编程中的C函数名通常是相关 ...
- 装X数学:高雅的数学表示
采用高雅的数学描述 转自于:研究生之路怎么走? 高雅的数学描述会提高你论文的等级和加强评审人对你基础功底的认可.例如泛函分析.集合.测度.度量空间和拓扑空间.现代代数.微分几何等数学方面的 ...
- node mysql es6/es7改造
本文js代码采取了ES6/ES7的写法,而不是commonJs的写法.支持一波JS的新语法.node版本的mysql驱动,通过npm i mysql安装.官网地址:https://github.com ...