java.lang.Object.clone()解读

一时失言乱红尘 2022-05-16 12:11 263阅读 0赞

原文: http://www.cnblogs.com/gw811/archive/2012/10/07/2712252.html

一、首先,看一下源码:

  1. 1 public class Object {
  2. 2 protected native Object clone() throws CloneNotSupportedException;
  3. 3 }

由源代码我们会发现:

  第一:**Object类的clone()方法是一个native方法**,native方法的效率一般来说都是远高于Java中的非native方法。这也解释了为什么要用Object中clone()方法而不是先new一个类,然后把原始对象中的信息复制到新对象中,虽然这也实现了clone功能。(JNI是Java Native Interface的 缩写。从Java 1.1开始,Java Native Interface (JNI)标准成为java平台的一部分,它允许Java代码和其他语言写的代码进行交互。JNI一开始是为了本地已编译语言,尤其是C和C++而设计的,但是它并不妨碍你使用其他语言,只要调用约定受支持就可以了。使用java与本地已编译的代码交互,通常会丧失平台可移植性。但是,有些情况下这样做是可以接受的,甚至是必须的,比如,使用一些旧的库,与硬件、操作系统进行交互,或者为了提高程序的性能。JNI标准至少保证本地代码能工作在任何Java 虚拟机实现下。)

  第二:Object类中的 clone()方法被protected修饰符修饰。这也意味着如果要应用 clone()方 法,必须继承Object类,在 Java中所有的类是缺省继承 Object类的,也就不用关心这点了。然后重载 clone()方法。还有一点要考虑的是为了让其它类能调用这个 clone类的 clone()方法,重载之后要把 clone()方法的属性设置为 public。

  第三:Object.clone()方法返回一个Object对象。我们必须进行强制类型转换才能得到我们需要的类型。

二、浅层复制与深层复制概念:

  浅层复制: 被复制的对象的所有成员属性都有与原来的对象相同的值,而所有的对其他对象的引用仍然指向原来的对象。换言之,浅层复制仅仅复制所考虑的对象,而不复制它所引用的对象。(概念不好理解,请结合下文的示例去理解)

  深层复制:被复制对象的所有变量都含有与原来的对象相同的值,除去那些引用其他对象的变量。那些引用其他对象的变量将指向被复制过的新对象,而不是原有的那些被引用的对象。换言之,深层复制要复制的对象引用的对象都复制一遍。

  Java中对象的克隆

  1)在派生类中实现Cloneable借口。

  2)为了获取对象的一份拷贝,我们可以利用Object类的clone方法。

  3)在派生类中覆盖积累的clone方法,声明为public。

  4)在派生类的clone方法中,调用super.clone()。

  实现Cloneable接口

  首先,看一下源码:  

  1. 1 public interface Cloneable {
  2. 2 }

  我们奇怪的发现Cloneable竟然是空的,那么我们为什么要实现Cloneable接口呢?其实Cloneable接口仅仅是一个标志,而且这个标志也仅仅是针对 Object类中 clone()方法的,如果 clone 类没有实现 Cloneable 接口,并调用了 Object 的 clone() 方法(也就是调用了 super.Clone() 方法),那么Object 的 clone() 方法就会抛出 CloneNotSupportedException 异常。

  程序示例分析:

  1. 1 public class Person {
  2. 2 private String name;
  3. 3 private int age;
  4. 4 public Person(){}
  5. 5 public Person(String name,int age){
  6. 6 this.name=name;
  7. 7 this.age=age;
  8. 8 }
  9. 9 public Object clone(){
  10. 10 Object o=null;
  11. 11 try {
  12. 12 o=super.clone();
  13. 13 } catch (CloneNotSupportedException e) {
  14. 14 e.printStackTrace();
  15. 15 }
  16. 16 return o;
  17. 17 }
  18. 18 public String getName() {
  19. 19 return name;
  20. 20 }
  21. 21 public void setName(String name) {
  22. 22 this.name = name;
  23. 23 }
  24. 24 public int getAge() {
  25. 25 return age;
  26. 26 }
  27. 27 public void setAge(int age) {
  28. 28 this.age = age;
  29. 29 }
  30. 30 }
  31. 1 public class PersonTest {
  32. 2 public static void main(String[] args) {
  33. 3 Person p1=new Person("zhangsan",18);
  34. 4 Person p2=(Person)p1.clone();
  35. 5 p2.setName("lis");
  36. 6 p2.setAge(20);
  37. 7 System.out.println("name="
  38. 8 +p1.getName()+",age="+p1.getAge());
  39. 9 //修改p2后,没有对p1产生影响。
  40. 10 }
  41. 11 }

 说明:

  1)为什么我们在派生类中覆盖Object的clone()方法时,一定要调用super.clone()呢?在运行时刻,Object中的clone()识别你要复制的是哪一个对象,然后为此对象分配空间,并进行对象的复制,将原始对象的内容一一复制到新对象的存储空间中。

  2)继承自java.lang.Object.clone()方法是浅层复制。一下代码可以证明之:

  1. 1 public class Student implements Cloneable {
  2. 2 private String name;
  3. 3 private int age;
  4. 4 private Professor pro;
  5. 5 public Student(){}
  6. 6 public Student(String name,int age,Professor pro){
  7. 7 this.name=name;
  8. 8 this.age=age;
  9. 9 this.pro=pro;
  10. 10 }
  11. 11 public Object clone(){
  12. 12 Object o=null;
  13. 13 try {
  14. 14 //Object中的clone()识别出你要复制的是哪一个对象。
  15. 15 o=super.clone();
  16. 16 } catch (CloneNotSupportedException e) {
  17. 17 System.out.println(e.toString());
  18. 18 }
  19. 19 return o;
  20. 20 }
  21. 21 public String getName() {
  22. 22 return name;
  23. 23 }
  24. 24 public void setName(String name) {
  25. 25 this.name = name;
  26. 26 }
  27. 27 public int getAge() {
  28. 28 return age;
  29. 29 }
  30. 30 public void setAge(int age) {
  31. 31 this.age = age;
  32. 32 }
  33. 33 public Professor getPro() {
  34. 34 return pro;
  35. 35 }
  36. 36 public void setPro(Professor pro) {
  37. 37 this.pro = pro;
  38. 38 }
  39. 39 }
  40. 40 class Professor{
  41. 41 private String name;
  42. 42 private int age;
  43. 43 public Professor(){}
  44. 44 public Professor(String name,int age){
  45. 45 this.name=name;
  46. 46 this.age=age;
  47. 47 }
  48. 48 public String getName() {
  49. 49 return name;
  50. 50 }
  51. 51 public void setName(String name) {
  52. 52 this.name = name;
  53. 53 }
  54. 54 public int getAge() {
  55. 55 return age;
  56. 56 }
  57. 57 public void setAge(int age) {
  58. 58 this.age = age;
  59. 59 }
  60. 60 }
  61. 1 public class StudentTest {
  62. 2 public static void main(String[] args) {
  63. 3 Professor p=new Professor("wangwu",50);
  64. 4 Student s1=new Student("zhangsan",18,p);
  65. 5 Student s2=(Student)s1.clone();
  66. 6 s2.getPro().setName("maer");
  67. 7 s2.getPro().setAge(40);
  68. 8 System.out.println("name="+s1.getPro().getName()
  69. 9 +",age="+s1.getPro().getAge());
  70. 10 //name=maer,age=40
  71. 11 }
  72. 12 }

  那么我们如何实现深层复制的克隆,即在修改s2.Professor时不影响s1.Professor?代码改进如下:

  1. 1 public class Student implements Cloneable {
  2. 2 private String name;
  3. 3 private int age;
  4. 4 Professor pro;
  5. 5 public Student(){}
  6. 6 public Student(String name,int age,Professor pro){
  7. 7 this.name=name;
  8. 8 this.age=age;
  9. 9 this.pro=pro;
  10. 10 }
  11. 11 public Object clone(){
  12. 12 Student o=null;
  13. 13 try {
  14. 14 //Object中的clone()识别出你要复制的是哪一个对象。
  15. 15 o=(Student)super.clone();
  16. 16 } catch (CloneNotSupportedException e) {
  17. 17 System.out.println(e.toString());
  18. 18 }
  19. 19 o.pro=(Professor)pro.clone();
  20. 20 return o;
  21. 21 }
  22. 22 public String getName() {
  23. 23 return name;
  24. 24 }
  25. 25 public void setName(String name) {
  26. 26 this.name = name;
  27. 27 }
  28. 28 public int getAge() {
  29. 29 return age;
  30. 30 }
  31. 31 public void setAge(int age) {
  32. 32 this.age = age;
  33. 33 }
  34. 34 public Professor getPro() {
  35. 35 return pro;
  36. 36 }
  37. 37 public void setPro(Professor pro) {
  38. 38 this.pro = pro;
  39. 39 }
  40. 40 }
  41. 41 class Professor implements Cloneable{
  42. 42 private String name;
  43. 43 private int age;
  44. 44 public Professor(){}
  45. 45 public Professor(String name,int age){
  46. 46 this.name=name;
  47. 47 this.age=age;
  48. 48 }
  49. 49 public Object clone(){
  50. 50 Object o=null;
  51. 51 try {
  52. 52 o=super.clone();
  53. 53 } catch (CloneNotSupportedException e) {
  54. 54 e.printStackTrace();
  55. 55 }
  56. 56 return o;
  57. 57 }
  58. 58 public String getName() {
  59. 59 return name;
  60. 60 }
  61. 61 public void setName(String name) {
  62. 62 this.name = name;
  63. 63 }
  64. 64 public int getAge() {
  65. 65 return age;
  66. 66 }
  67. 67 public void setAge(int age) {
  68. 68 this.age = age;
  69. 69 }
  70. 70 }
  71. public class StudentTest {
  72. public static void main(String[] args) {
  73. Professor p=new Professor("wangwu",50);
  74. Student s1=new Student("zhangsan",18,p);
  75. Student s2=(Student)s1.clone();
  76. s2.getPro().setName("maer");
  77. s2.getPro().setAge(40);
  78. System.out.println("name="+s1.getPro().getName()
  79. +",age="+s1.getPro().getAge());
  80. //name=wangwu,age=50
  81. }
  82. }

  

利用串行化来实现深层复制

  把对象写到流中的过程是串行化(Serilization)过程,而把对象从流中读出来是并行化(Deserialization)过程。应当指出的是,写在流中的是对象的一个拷贝,而原来对象仍然存在JVM里面。

  在Java语言里深层复制一个对象,常常可以先使对象实现Serializable接口,然后把对象(实际上只是对象的一个拷贝)写到一个流中,再从流中读出来,便可以重建对象。

  这样做的前提是对象以及对象内部所有引用到的对象都是可串行化的,否则,就需要仔细考察那些不可串行化的对象是否设成transient,从而将之排除在复制过程之外。代码改进如下:

  1. 1 public class Student implements Serializable {
  2. 2 private String name;
  3. 3 private int age;
  4. 4 Professor pro;
  5. 5 public Student(){}
  6. 6 public Student(String name,int age,Professor pro){
  7. 7 this.name=name;
  8. 8 this.age=age;
  9. 9 this.pro=pro;
  10. 10 }
  11. 11 public Object deepClone() throws IOException, ClassNotFoundException{
  12. 12 //将对象写到流中
  13. 13 ByteArrayOutputStream bo=new ByteArrayOutputStream();
  14. 14 ObjectOutputStream oo=new ObjectOutputStream(bo);
  15. 15 oo.writeObject(this);
  16. 16 //从流中读出来
  17. 17 ByteArrayInputStream bi=new ByteArrayInputStream(bo.toByteArray());
  18. 18 ObjectInputStream oi=new ObjectInputStream(bi);
  19. 19 return oi.readObject();
  20. 20 }
  21. 21 public String getName() {
  22. 22 return name;
  23. 23 }
  24. 24 public void setName(String name) {
  25. 25 this.name = name;
  26. 26 }
  27. 27 public int getAge() {
  28. 28 return age;
  29. 29 }
  30. 30 public void setAge(int age) {
  31. 31 this.age = age;
  32. 32 }
  33. 33 public Professor getPro() {
  34. 34 return pro;
  35. 35 }
  36. 36 public void setPro(Professor pro) {
  37. 37 this.pro = pro;
  38. 38 }
  39. 39 }
  40. 40 class Professor implements Serializable{
  41. 41 private String name;
  42. 42 private int age;
  43. 43 public Professor(){}
  44. 44 public Professor(String name,int age){
  45. 45 this.name=name;
  46. 46 this.age=age;
  47. 47 }
  48. 48 public String getName() {
  49. 49 return name;
  50. 50 }
  51. 51 public void setName(String name) {
  52. 52 this.name = name;
  53. 53 }
  54. 54 public int getAge() {
  55. 55 return age;
  56. 56 }
  57. 57 public void setAge(int age) {
  58. 58 this.age = age;
  59. 59 }
  60. 60 }
  61. 1 public class StudentTest {
  62. 2 public static void main(String[] args) throws IOException, ClassNotFoundException {
  63. 3 Professor p=new Professor("wangwu",50);
  64. 4 Student s1=new Student("zhangsan",18,p);
  65. 5 Student s2=(Student)s1.deepClone();
  66. 6 s2.getPro().setName("maer");
  67. 7 s2.getPro().setAge(40);
  68. 8 System.out.println("name="+s1.getPro().getName()
  69. 9 +",age="+s1.getPro().getAge());
  70. 10 //name=wangwu,age=50
  71. 11 }
  72. 12 }

  继续深究:{一下是个人未能想明白的一些问题,网络上也没能给出很好的解释}
  1、数组:(以int[]为例):

  1. 1 public class ArrayClone {
  2. 2 public static void main(String[] args) {
  3. 3 int[] a1={1,2,3,4};
  4. 4 int[] a2=a1.clone();
  5. 5 System.out.println(Arrays.toString(a2));
  6. 6 //[1, 2, 3, 4]
  7. 7 String[] s1={"hello","china"};
  8. 8 String[] s2=s1.clone();
  9. 9 System.out.println(Arrays.toString(s2));
  10. 10 //[hello, china]
  11. 11 Object[] o1={new Object(),new Object()};
  12. 12 Object[] o2=o1.clone();
  13. 13 System.out.println(Arrays.toString(o2));
  14. 14 //[java.lang.Object@1fc4bec, java.lang.Object@dc8569]
  15. 15 }
  16. 16 }

  我们发现Java数组有clone()方法,而且不需要我们去进行强制类型转换,Java底层是怎样实现数据结构这个功能的?

  1. 1 public class ArrayClone {
  2. 2 public static void main(String[] args) {
  3. 3 Person p1=new Person("wangwu",18);
  4. 4 Person p2=new Person("lisi",28);
  5. 5 Person[] ps1={p1,p2};
  6. 6 Person[] ps2=ps1.clone();
  7. 7 ps2[0].setName("wanghao");
  8. 8 ps2[0].setAge(22);
  9. 9 System.out.println("name="+p1.getName()+",age="+p1.getAge());
  10. 10 //name=wanghao,age=22
  11. 11 }
  12. 12 }

  由测试可知,Java数组只具备浅层复制的功能。

  2、String类

  1. 1 public class StringClone {
  2. 2 public static void main(String[] args) {
  3. 3 String str1="wang";
  4. 4 //String str2=(String)str1.clone();
  5. 5 //编译错误,String类没有clone方法
  6. 6 }
  7. 7 }

  查看源代码,我们可知,String类并没有重载Object类的clone方法。虽然,String和Object都在java.lang包中,但是我们的测试类StringClone不在java.lang包中,因此,str.clone()时会出现编译错误。继续进行:

  1. 1 public class Dog {
  2. 2 private String name;
  3. 3 private int age;
  4. 4 public Dog(){}
  5. 5 public Dog(String name,int age){
  6. 6 this.name=name;
  7. 7 this.age=age;
  8. 8 }
  9. 9 public static void main(String[] args) {
  10. 10 Dog dog1=new Dog("dog1",5);
  11. 11 Dog dog2=null;
  12. 12 try {
  13. 13 dog2=(Dog)dog1.clone();
  14. 14 } catch (CloneNotSupportedException e) {
  15. 15 // TODO Auto-generated catch block
  16. 16 e.printStackTrace();
  17. 17 }
  18. 18 System.out.println(dog2.getName()+","+dog2.getAge());
  19. 19 }
  20. 20 public String getName() {
  21. 21 return name;
  22. 22 }
  23. 23 public void setName(String name) {
  24. 24 this.name = name;
  25. 25 }
  26. 26 public int getAge() {
  27. 27 return age;
  28. 28 }
  29. 29 public void setAge(int age) {
  30. 30 this.age = age;
  31. 31 }
  32. 32 }

  我们惊奇的发现,dog1.clone();并没有出现变异错误,我们随便创建的类具有clone方法,这又是怎么回事?

  虽然没编译错误,但是运行时出错,如下所示:

  1. 1 java.lang.CloneNotSupportedException: com.clone.Dog
  2. 2 at java.lang.Object.clone(Native Method)
  3. 3 at com.clone.Dog.main(Dog.java:15)
  4. 4 Exception in thread "main" java.lang.NullPointerException
  5. 5 at com.clone.Dog.main(Dog.java:20)

发表评论

表情:
评论列表 (有 0 条评论,263人围观)

还没有评论,来说两句吧...

相关阅读

    相关 ResT解读

    > 最近的一篇基于Transformer的工作,由南京大学的研究者提出一种高效的视觉Transformer结构,设计思想类似ResNet,称为ResT,这是我个人觉得值得关注的

    相关 SiamMOT解读

    > AWS的一篇新的MOT工作,将孪生跟踪器引入多目标跟踪中进行运动建模并获得了SOTA表现。 简介 通过引入一个基于区域的孪生多目标跟踪网络,设计了一个新的onlin

    相关 GCT解读

    > 浙江大学等机构发布的一篇收录于CVPR2021的文章,提出了一种新的通道注意力结构,在几乎不引入参数的前提下优于大多SOTA通道注意力模型,如SE、ECA等。这篇文章虽然叫

    相关 ThreadLocal解读

    先,ThreadLocal 不是用来解决共享对象的多线程访问问题的,一般情况下,通过ThreadLocal.set() 到线程中的对象是该线程自己使用的对象,其他线程是不需要访

    相关 PaxosStore解读

    PaxosStore解读 1.   QuorumKV (NWR)       微信有大量分布式存储(QuorumKV)使用这个算法保证一致性,我们对这个算法做了改

    相关 解读基金

    第一章 投资的准备 咱们该投资吗 如果不投资通货膨胀会侵蚀你的资产 投资能产生复利收益,长期稳定的收益会产生巨大的财富 什么是开放式基金 基金:把