当前位置:   article > 正文

java基础学习之对象复制与对象序列化

java 拷贝一个对象使用clone还是json序列化

        在工作中,会经常涉及到对象的拷贝和序列化,看似平常普通的知识点,其实还是有很多需要我们去学习、研究、注意的,对日后学习很多技术都有很大的帮助,今天就整理一下有关对象拷贝和序列化的知识。

        对象的复制有三种方式:引用复制,clone复制,序列化复制

1. 引用复制

        新建一个实体类如下:

  1. public class Customer {
  2. private String userName;
  3. private String password;
  4. public String getUserName() {
  5. return userName;
  6. }
  7. public void setUserName(String userName) {
  8. this.userName = userName;
  9. }
  10. public String getPassword() {
  11. return password;
  12. }
  13. public void setPassword(String password) {
  14. this.password = password;
  15. }
  16. @Override
  17. public boolean equals(Object o) {
  18. if (this == o) return true;
  19. if (o == null || getClass() != o.getClass()) return false;
  20. Customer customer = (Customer) o;
  21. return Objects.equals(userName, customer.userName) &&
  22. Objects.equals(password, customer.password);
  23. }
  24. @Override
  25. public int hashCode() {
  26. return Objects.hash(userName, password);
  27. }
  28. @Override
  29. public String toString() {
  30. return "Customer{" +
  31. "userName='" + userName + '\'' +
  32. ", password='" + password + '\'' +
  33. '}';
  34. }
  35. }

测试引用复制

  1. public static void main(String[] args) {
  2. Customer c1 = new Customer();
  3. c1.setUserName("张三");
  4. c1.setPassword("123456");
  5. Customer c2 = c1;
  6. System.out.println(c1.equals(c2));
  7. System.out.println(c1 == c2);
  8. System.out.println("c1 = " + c1);
  9. System.out.println("c2 = " + c2);
  10. }
  11. D:\java\jdk1.8\bin\java.exe ...
  12. true
  13. true
  14. c1 = Customer{userName='张三', password='123456'}
  15. c2 = Customer{userName='张三', password='123456'}
  16. Process finished with exit code 0

引用复制 由于是两个对象的引用是相同,共同指向堆中的同一个对象,所以其中一个对象修改属性,会影响另一个对象的属性

  1. public static void main(String[] args) {
  2. Customer c1 = new Customer();
  3. c1.setUserName("张三");
  4. c1.setPassword("123456");
  5. Customer c2 = c1;
  6. c2.setPassword("654321");
  7. System.out.println(c1.equals(c2));
  8. System.out.println(c1 == c2);
  9. System.out.println("c1 = " + c1);
  10. System.out.println("c2 = " + c2);
  11. }
  12. D:\java\jdk1.8\bin\java.exe ...
  13. true
  14. true
  15. c1 = Customer{userName='张三', password='654321'}
  16. c2 = Customer{userName='张三', password='654321'}
  17. Process finished with exit code 0

所以使用引用复制对象时需要注意这一点.

2. clone拷贝复制

        clone拷贝复制分为浅拷贝和深拷贝

    2.1 浅拷贝

        新建实体类实现cloneable接口,重写clone方法

  1. public class Customer implements Cloneable {
  2. private String userName;
  3. private String password;
  4. public String getUserName() {
  5. return userName;
  6. }
  7. public void setUserName(String userName) {
  8. this.userName = userName;
  9. }
  10. public String getPassword() {
  11. return password;
  12. }
  13. public void setPassword(String password) {
  14. this.password = password;
  15. }
  16. @Override
  17. protected Object clone() throws CloneNotSupportedException {
  18. return super.clone();
  19. }
  20. @Override
  21. public boolean equals(Object o) {
  22. if (this == o) return true;
  23. if (o == null || getClass() != o.getClass()) return false;
  24. Customer customer = (Customer) o;
  25. return Objects.equals(userName, customer.userName) &&
  26. Objects.equals(password, customer.password);
  27. }
  28. @Override
  29. public int hashCode() {
  30. return Objects.hash(userName, password);
  31. }
  32. @Override
  33. public String toString() {
  34. return "Customer{" +
  35. "userName='" + userName + '\'' +
  36. ", password='" + password + '\'' +
  37. '}';
  38. }
  39. }

测试浅拷贝

  1. public static void main(String[] args) throws CloneNotSupportedException {
  2. Customer c1 = new Customer();
  3. c1.setUserName("张三");
  4. c1.setPassword("123456");
  5. Customer c2 = (Customer)c1.clone();
  6. System.out.println(c1.equals(c2));
  7. System.out.println(c1 == c2);
  8. System.out.println("c1 = " + c1);
  9. System.out.println("c2 = " + c2);
  10. }
  11. D:\java\jdk1.8\bin\java.exe ...
  12. true
  13. false
  14. c1 = Customer{userName='张三', password='123456'}
  15. c2 = Customer{userName='张三', password='123456'}
  16. Process finished with exit code 0

从面的代码可以看出浅拷贝是重新生成了一个对象,两个对象的引用并不相同,这一点和引用复制不同,我们再试一下浅拷贝是否存在和引用复制一样的问题

  1. public static void main(String[] args) throws CloneNotSupportedException {
  2. Customer c1 = new Customer();
  3. c1.setUserName("张三");
  4. c1.setPassword("123456");
  5. Customer c2 = (Customer)c1.clone();
  6. c2.setPassword("654321");
  7. System.out.println(c1.equals(c2));
  8. System.out.println(c1 == c2);
  9. System.out.println("c1 = " + c1);
  10. System.out.println("c2 = " + c2);
  11. }
  12. D:\java\jdk1.8\bin\java.exe ...
  13. false
  14. false
  15. c1 = Customer{userName='张三', password='123456'}
  16. c2 = Customer{userName='张三', password='654321'}
  17. Process finished with exit code 0

这里我们可以看出浅拷贝不会出现和引用复制一样的问题,因为来个对象指向的引用并不相同.

但是浅拷贝也一样存在他自己的问题.

我们重新新建一个实体类,在实体类中加入引用其他类的成员变量

  1. public class Customer implements Cloneable {
  2. private String userName;
  3. private String password;
  4. private User user;
  5. public String getUserName() {
  6. return userName;
  7. }
  8. public void setUserName(String userName) {
  9. this.userName = userName;
  10. }
  11. public String getPassword() {
  12. return password;
  13. }
  14. public void setPassword(String password) {
  15. this.password = password;
  16. }
  17. @Override
  18. protected Object clone() throws CloneNotSupportedException {
  19. return super.clone();
  20. }
  21. public User getUser() {
  22. return user;
  23. }
  24. public void setUser(User user) {
  25. this.user = user;
  26. }
  27. @Override
  28. public boolean equals(Object o) {
  29. if (this == o) return true;
  30. if (o == null || getClass() != o.getClass()) return false;
  31. Customer customer = (Customer) o;
  32. return Objects.equals(userName, customer.userName) &&
  33. Objects.equals(password, customer.password) &&
  34. Objects.equals(user, customer.user);
  35. }
  36. @Override
  37. public int hashCode() {
  38. return Objects.hash(userName, password, user);
  39. }
  40. @Override
  41. public String toString() {
  42. return "Customer{" +
  43. "userName='" + userName + '\'' +
  44. ", password='" + password + '\'' +
  45. ", user=" + user +
  46. '}';
  47. }
  48. }
  49. public class User {
  50. private int age;
  51. private int sex;
  52. public int getAge() {
  53. return age;
  54. }
  55. @Override
  56. public boolean equals(Object o) {
  57. if (this == o) return true;
  58. if (o == null || getClass() != o.getClass()) return false;
  59. User user = (User) o;
  60. return age == user.age &&
  61. sex == user.sex;
  62. }
  63. @Override
  64. public int hashCode() {
  65. return Objects.hash(age, sex);
  66. }
  67. public void setAge(int age) {
  68. this.age = age;
  69. }
  70. public int getSex() {
  71. return sex;
  72. }
  73. public void setSex(int sex) {
  74. this.sex = sex;
  75. }
  76. @Override
  77. public String toString() {
  78. return "User{" +
  79. "age=" + age +
  80. ", sex=" + sex +
  81. '}';
  82. }
  83. }

然后对实体类进行浅拷贝

  1. public static void main(String[] args) throws CloneNotSupportedException {
  2. Customer c1 = new Customer();
  3. c1.setUserName("张三");
  4. c1.setPassword("123456");
  5. User user = new User();
  6. user.setAge(18);
  7. user.setSex(0);
  8. c1.setUser(user);
  9. Customer c2 = (Customer)c1.clone();
  10. System.out.println(c1.equals(c2));
  11. System.out.println(c1 == c2);
  12. System.out.println("c1 = " + c1);
  13. System.out.println("c2 = " + c2);
  14. user.setSex(1);
  15. user.setAge(16);
  16. System.out.println("c1_1 = " + c1);
  17. System.out.println("c2_1 = " + c2);
  18. System.out.println(c1.getUser() == c2.getUser());
  19. System.out.println(c1.getUser().equals(c2.getUser()));
  20. }
  21. D:\java\jdk1.8\bin\java.exe ...
  22. true
  23. false
  24. c1 = Customer{userName='张三', password='123456', user=User{age=18, sex=0}}
  25. c2 = Customer{userName='张三', password='123456', user=User{age=18, sex=0}}
  26. c1_1 = Customer{userName='张三', password='123456', user=User{age=16, sex=1}}
  27. c2_1 = Customer{userName='张三', password='123456', user=User{age=16, sex=1}}
  28. true
  29. true
  30. Process finished with exit code 0

我们发现clone方法之后引用类型的成员变量并没有被拷贝出一个新的对象,而是直接被引用过来的,修改任何一个对象的引用变量,另一个对象的引用变量都会改变,这里是秉着不对引用变量的对象强加意义和不改变其设计原则的原则,所以并没有对引用的对象进行clone,这里如果需要对引用变量进行clone,也就是深拷贝就需要将引用变量的对象得类也实现cloneable接口,并重写clone方法,这样就会在clone时将引用对象也一起拷贝.

2.2  深拷贝

代码如下:

  1. public class Customer implements Cloneable {
  2. private String userName;
  3. private String password;
  4. private User user;
  5. public String getUserName() {
  6. return userName;
  7. }
  8. public void setUserName(String userName) {
  9. this.userName = userName;
  10. }
  11. public String getPassword() {
  12. return password;
  13. }
  14. public void setPassword(String password) {
  15. this.password = password;
  16. }
  17. @Override
  18. protected Object clone() throws CloneNotSupportedException {
  19. Customer customer = (Customer)super.clone();
  20. customer.user = (User)user.clone();
  21. return customer;
  22. }
  23. public User getUser() {
  24. return user;
  25. }
  26. public void setUser(User user) {
  27. this.user = user;
  28. }
  29. @Override
  30. public boolean equals(Object o) {
  31. if (this == o) return true;
  32. if (o == null || getClass() != o.getClass()) return false;
  33. Customer customer = (Customer) o;
  34. return Objects.equals(userName, customer.userName) &&
  35. Objects.equals(password, customer.password) &&
  36. Objects.equals(user, customer.user);
  37. }
  38. @Override
  39. public int hashCode() {
  40. return Objects.hash(userName, password, user);
  41. }
  42. @Override
  43. public String toString() {
  44. return "Customer{" +
  45. "userName='" + userName + '\'' +
  46. ", password='" + password + '\'' +
  47. ", user=" + user +
  48. '}';
  49. }
  50. }
  51. public class User implements Cloneable{
  52. private int age;
  53. private int sex;
  54. public int getAge() {
  55. return age;
  56. }
  57. @Override
  58. public boolean equals(Object o) {
  59. if (this == o) return true;
  60. if (o == null || getClass() != o.getClass()) return false;
  61. User user = (User) o;
  62. return age == user.age &&
  63. sex == user.sex;
  64. }
  65. @Override
  66. public int hashCode() {
  67. return Objects.hash(age, sex);
  68. }
  69. public void setAge(int age) {
  70. this.age = age;
  71. }
  72. public int getSex() {
  73. return sex;
  74. }
  75. public void setSex(int sex) {
  76. this.sex = sex;
  77. }
  78. @Override
  79. public String toString() {
  80. return "User{" +
  81. "age=" + age +
  82. ", sex=" + sex +
  83. '}';
  84. }
  85. @Override
  86. protected Object clone() throws CloneNotSupportedException {
  87. return super.clone();
  88. }
  89. }
  90. public static void main(String[] args) throws CloneNotSupportedException {
  91. Customer c1 = new Customer();
  92. c1.setUserName("张三");
  93. c1.setPassword("123456");
  94. User user = new User();
  95. user.setAge(18);
  96. user.setSex(0);
  97. c1.setUser(user);
  98. Customer c2 = (Customer)c1.clone();
  99. System.out.println(c1.equals(c2));
  100. System.out.println(c1 == c2);
  101. System.out.println("c1 = " + c1);
  102. System.out.println("c2 = " + c2);
  103. user.setAge(16);
  104. user.setSex(1);
  105. System.out.println("c1_1 = " + c1);
  106. System.out.println("c2_1 = " + c2);
  107. System.out.println(c1.getUser().equals(c2.getUser()));
  108. System.out.println(c1.getUser() == c2.getUser());
  109. }
  110. D:\java\jdk1.8\bin\java.exe ...
  111. true
  112. false
  113. c1 = Customer{userName='张三', password='123456', user=User{age=18, sex=0}}
  114. c2 = Customer{userName='张三', password='123456', user=User{age=18, sex=0}}
  115. c1_1 = Customer{userName='张三', password='123456', user=User{age=16, sex=1}}
  116. c2_1 = Customer{userName='张三', password='123456', user=User{age=18, sex=0}}
  117. false
  118. false
  119. Process finished with exit code 0

3.  序列化复制

序列化是将对象的拷贝写到流中,原对象还存在于内存中

反序列化是将流中的对象读到内存中

将序列化主要目的是为了实现对象的跨域跨平台传输

java实现RMI、JMS等的基础

学习一下java中关于对象的序列化知识.

常用序列化方式有:jdk, json, xml, hessian, kryo, thrift, protostuff, fst.选择什么方式的序列化主要从以下几点去考虑:跨平台,序列化的性能,序列化文件大小

jdk序列化的实现方式: 实现序列化接口

  1. public class Customer implements Serializable {
  2. private String userName;
  3. private String password;
  4. public String getUserName() {
  5. return userName;
  6. }
  7. public void setUserName(String userName) {
  8. this.userName = userName;
  9. }
  10. public String getPassword() {
  11. return password;
  12. }
  13. public void setPassword(String password) {
  14. this.password = password;
  15. }
  16. @Override
  17. public boolean equals(Object o) {
  18. if (this == o) return true;
  19. if (o == null || getClass() != o.getClass()) return false;
  20. Customer customer = (Customer) o;
  21. return Objects.equals(userName, customer.userName) &&
  22. Objects.equals(password, customer.password);
  23. }
  24. @Override
  25. public int hashCode() {
  26. return Objects.hash(userName, password);
  27. }
  28. @Override
  29. public String toString() {
  30. return "Customer{" +
  31. "userName='" + userName + '\'' +
  32. ", password='" + password + '\'' +
  33. '}';
  34. }
  35. }
  36. public static void main(String[] args) {
  37. Customer c1 = new Customer();
  38. c1.setUserName("张三");
  39. c1.setPassword("123456");
  40. ObjectOutputStream os = null;
  41. try {
  42. os = new ObjectOutputStream(new FileOutputStream("E:\\新建文件夹\\test.txt"));
  43. os.writeObject(c1);
  44. } catch (IOException e) {
  45. e.printStackTrace();
  46. }finally {
  47. try {
  48. os.close();
  49. } catch (IOException e) {
  50. e.printStackTrace();
  51. }
  52. }
  53. }

执行完后会对象写到对应位置文件中

然后我们写在将文件中的对象反序列化到内存中

  1. public static void main(String[] args) {
  2. ObjectInputStream is = null;
  3. Customer customer;
  4. try {
  5. is = new ObjectInputStream(new FileInputStream("E:\\新建文件夹\\test.txt"));
  6. customer = (Customer)is.readObject();
  7. System.out.println(customer);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. }finally {
  11. try {
  12. is.close();
  13. } catch (IOException e) {
  14. e.printStackTrace();
  15. }
  16. }
  17. }
  18. D:\java\jdk1.8\bin\java.exe ...
  19. Customer{userName='张三', password='123456'}
  20. Process finished with exit code 0

序列化需要注意的几点

    3.1 SerialVersionUID(该字段必须是静态 (static)、最终 (final) 的 long 型字段)用于对象的版本控制。当您添加或修改类中的任何字段时,已经序列化的类将无法恢复,因为serialVersionUID已为新类生成与旧的序列化对象将不同。Java序列化过程依赖于正确的serialVersionUID恢复序列化对象的状态,并在serialVersionUID不匹配时抛出java.io.InvalidClassException 异常。

添加版本号之后将对象序列化到文件,再修改对象属性,反序列化得到的还是修改前的对象,代码结果如图

  1. D:\java\jdk1.8\bin\java.exe
  2. Customer{userName='张三', password='123456', age='null'}
  3. Process finished with exit code 0

挡序列化一个类的实例后,希望更改一个字段或添加一个字段,不设置serialVersionUID,所做的任何更改都将导致无法反序化旧有实例,并在反序列化时抛出一个异常。如果你添加了serialVersionUID,在反序列旧有实例时,新添加或更改的字段值将设为初始化值(对象为null,基本类型为相应的初始默认值),字段被删除将不设置。

序列化和反序列化序列号不一致,会抛异常

  1. D:\java\jdk1.8\bin\java.exe ...
  2. java.io.InvalidClassException: Customer; local class incompatible: stream classdesc serialVersionUID = 1, local class serialVersionUID = 2
  3. at java.io.ObjectStreamClass.initNonProxy(ObjectStreamClass.java:699)
  4. at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1885)
  5. at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
  6. at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
  7. at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
  8. at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
  9. at Demo.main(Demo.java:16)
  10. Process finished with exit code 0

    3.2 transient修饰符仅适用于变量,不适用于方法和类。在序列化时,如果我们不想序列化特定变量以满足安全约束,那么我们应该将该变量声明为transient。执行序列化时,JVM会忽略transient变量的原始值并将默认值保存到文件中。因此,transient意味着不要序列化。

将password加transient修饰后,代码运行结果

  1. D:\java\jdk1.8\bin\java.exe ...
  2. Customer{userName='张三', password='null'}
  3. Process finished with exit code 0

    3.3 静态变量不是对象状态的一部分,因此它不参与序列化

将userName加static修饰后,代码运行结果

  1. D:\java\jdk1.8\bin\java.exe ...
  2. Customer{userName='null', password='123456'}
  3. Process finished with exit code 0

    3.4 当一个父类实现序列化,子类自动实现序列化,不需要显式实现Serializable接口

 

转载于:https://my.oschina.net/u/4149810/blog/3065435

本文内容由网友自发贡献,转载请注明出处:https://www.wpsshop.cn/w/笔触狂放9/article/detail/68575
推荐阅读
相关标签
  

闽ICP备14008679号