java Enhancement (5) - - Using Serialization to Realize Copy of Objects

Keywords: Java iOS

We know that Java The Cloneable interface exists, and the classes that implement it all have the ability to be copied. At the same time, the copy is done in memory, which is faster in performance than the object generated directly by new. Especially in the generation of large objects, the performance improvement is very obvious. However, we know that copy can be divided into deep copy and shallow copy, but shallow copy has the problem of incomplete copy of object attributes. For deep and shallow copies, please refer to here: Shallow and deep copies of java

1. Shallow copy problem

Let's first look at the following code:

  1. public class Person implements Cloneable{  
  2.     /** Name**/  
  3.     private String name;  
  4.       
  5.     /** E-mail**/  
  6.     private Email email;  
  7.   
  8.     public String getName() {  
  9.         return name;  
  10.     }  
  11.   
  12.     public void setName(String name) {  
  13.         this.name = name;  
  14.     }  
  15.   
  16.     public Email getEmail() {  
  17.         return email;  
  18.     }  
  19.   
  20.     public void setEmail(Email email) {  
  21.         this.email = email;  
  22.     }  
  23.       
  24.     public Person(String name,Email email){  
  25.         this.name  = name;  
  26.         this.email = email;  
  27.     }  
  28.       
  29.     public Person(String name){  
  30.         this.name = name;  
  31.     }  
  32.   
  33.     protected Person clone() {  
  34.         Person person = null;  
  35.         try {  
  36.             person = (Person) super.clone();  
  37.         } catch (CloneNotSupportedException e) {  
  38.             e.printStackTrace();  
  39.         }  
  40.           
  41.         return person;  
  42.     }  
  43. }  
  44.   
  45. public class Client {  
  46.     public static void main(String[] args) {  
  47.         //Write an email  
  48.         Email email = new Email("Please attend the meeting.","Please contact today 12:30 Attend the meeting in Conference Room 2...");  
  49.           
  50.         Person person1 =  new Person("Zhang San",email);  
  51.           
  52.         Person person2 =  person1.clone();  
  53.         person2.setName("Li Si");  
  54.         Person person3 =  person1.clone();  
  55.         person3.setName("Wang Wu");  
  56.           
  57.         System.out.println(person1.getName() + "The content of the email is:" + person1.getEmail().getContent());  
  58.         System.out.println(person2.getName() + "The content of the email is:" + person2.getEmail().getContent());  
  59.         System.out.println(person3.getName() + "The content of the email is:" + person3.getEmail().getContent());  
  60.     }  
  61. }  
  62. --------------------  
  63. Output:  
  64. The content of Zhang San's e-mail is: Please contact today.12:30Attend the meeting in Conference Room 2...  
  65. Li Si's e-mail content is: Please contact today12:30Attend the meeting in Conference Room 2...  
  66. Wang Wu's e-mail content is: Please contact today12:30Attend the meeting in Conference Room 2...  

In this application, we first define an email and send it to three people, Zhang San, Li Si and Wang Wu. Because they use the same email and have different names, we use Zhang San to copy Li Si and Wang Wu objects and change their names. There's nothing wrong with the program up to this point, but if we need Zhang San to arrive 30 minutes in advance, we can modify the contents of the mail.

  1. public class Client {  
  2.     public static void main(String[] args) {  
  3.         //Write an email  
  4.         Email email = new Email("Please attend the meeting.","Please contact today 12:30 Attend the meeting in Conference Room 2...");  
  5.           
  6.         Person person1 =  new Person("Zhang San",email);  
  7.           
  8.         Person person2 =  person1.clone();  
  9.         person2.setName("Li Si");  
  10.         Person person3 =  person1.clone();  
  11.         person3.setName("Wang Wu");  
  12.           
  13.         person1.getEmail().setContent("Please contact today 12:00 Attend the meeting in Conference Room 2...");  
  14.           
  15.         System.out.println(person1.getName() + "The content of the email is:" + person1.getEmail().getContent());  
  16.         System.out.println(person2.getName() + "The content of the email is:" + person2.getEmail().getContent());  
  17.         System.out.println(person3.getName() + "The content of the email is:" + person3.getEmail().getContent());  
  18.     }  
  19. }  
Here, we also use Zhang San as the object to realize the copy of Li Si and Wang Wu. Finally, we change the content of Zhang San's e-mail to: Please attend the meeting with today's 12:00 to Conference Room 2.... But the result is:

  1. The content of Zhang San's e-mail is: Please attend the meeting from 12:00 to Conference Room 2 today.
  2. Li Si's e-mail content is: Please attend the meeting from 12:00 to Conference Room 2 today.
  3. Wang Wu's e-mail message is: Please attend the meeting from 12:00 to Conference Room 2 today.

Here we wonder why Li Si and Wang Wu's e-mail content has changed too. It would be advisable for them to arrive 30 minutes earlier!

In fact, the key to the problem lies in the clone() method, which we know uses the clone() method of Object class, but there is a flaw in this method. It does not copy all the attributes of the object, but selectively copies. The basic rules are as follows:

1. Basic types

If a variable is of a very basic type, copy its values, such as int, float, etc.

2. Objects

If a variable is an instance object, copy its address reference, that is to say, the new object and the original object are public instance variables.

String string

If the variable is a String string, copy its address reference. But when modified, it will regenerate a new string from the string pool, and the original Purple Capital object will remain unchanged.

Based on the above rules, we can easily find the problem. They share an object. If Zhang San modifies the content of the email, Li Si and Wang Wu will also modify it, so the above situation will occur. In this case, we can still solve the problem by creating a new object in the clone() method and then referring to it by Zhang San.

  1. protected Person clone() {  
  2.         Person person = null;  
  3.         try {  
  4.             person = (Person) super.clone();  
  5.             person.setEmail(new Email(person.getEmail().getObject(),person.getEmail().getContent()));  
  6.         } catch (CloneNotSupportedException e) {  
  7.             e.printStackTrace();  
  8.         }  
  9.           
  10.         return person;  
  11.     }  

Therefore, shallow copy is only a simple copy mechanism provided by Java, which is not easy to use directly.

There is still a problem with the above solution. If there are a large number of objects generated by copying in our system, if we write a clone() method for each class, we will need to make deep copies and create a large number of new objects, this project is very large. Here we can use serialization to achieve the copy of objects.

2. Implementing object copy by serialization

How to use serialization to complete object copy? It is easy to copy byte stream in memory. Write the parent object into a byte stream and read it out from the byte stream so that a new object can be created, and there is no problem of reference sharing between the new object and the parent object, so that the deep copy of the object can be realized.

  1. public class CloneUtils {  
  2.     @SuppressWarnings("unchecked")  
  3.     public static <T extends Serializable> T clone(T obj){  
  4.         T cloneObj = null;  
  5.         try {  
  6.             //Write byte stream  
  7.             ByteArrayOutputStream out = new ByteArrayOutputStream();  
  8.             ObjectOutputStream obs = new ObjectOutputStream(out);  
  9.             obs.writeObject(obj);  
  10.             obs.close();  
  11.               
  12.             //Allocate memory, write to the original object, and generate new objects  
  13.             ByteArrayInputStream ios = new ByteArrayInputStream(out.toByteArray());  
  14.             ObjectInputStream ois = new ObjectInputStream(ios);  
  15.             //Returns the generated new object  
  16.             cloneObj = (T) ois.readObject();  
  17.             ois.close();  
  18.         } catch (Exception e) {  
  19.             e.printStackTrace();  
  20.         }  
  21.         return cloneObj;  
  22.     }  
  23. }  

Objects using the tool class must implement the Serializable interface, otherwise there is no way to achieve cloning.

  1. public class Person implements Serializable{  
  2.     private static final long serialVersionUID = 2631590509760908280L;  
  3.   
  4.     ..................  
  5.     //clone() removal method
  6.   
  7. }  
  8.   
  9. public class Email implements Serializable{  
  10.     private static final long serialVersionUID = 1267293988171991494L;  
  11.       
  12.     ....................  
  13. }  

Therefore, the clone() method can be implemented by using the tool class as long as the Serializable interface is implemented, without inheriting the Cloneable interface.

  1. public class Client {  
  2.     public static void main(String[] args) {  
  3.         //Write an email  
  4.         Email email = new Email("Please attend the meeting.","Please contact today 12:30 Attend the meeting in Conference Room 2...");  
  5.           
  6.         Person person1 =  new Person("Zhang San",email);  
  7.           
  8.         Person person2 =  CloneUtils.clone(person1);  
  9.         person2.setName("Li Si");  
  10.         Person person3 =  CloneUtils.clone(person1);  
  11.         person3.setName("Wang Wu");  
  12.         person1.getEmail().setContent("Please contact today 12:00 Attend the meeting in Conference Room 2...");  
  13.           
  14.         System.out.println(person1.getName() + "The content of the email is:" + person1.getEmail().getContent());  
  15.         System.out.println(person2.getName() + "The content of the email is:" + person2.getEmail().getContent());  
  16.         System.out.println(person3.getName() + "The content of the email is:" + person3.getEmail().getContent());  
  17.     }  
  18. }  
  19. -------------------  
  20. Output:  
  21. The content of Zhang San's e-mail is: Please contact today.12:00Attend the meeting in Conference Room 2...  
  22. Li Si's e-mail content is: Please contact today12:30Attend the meeting in Conference Room 2...  
  23. Wang Wu's e-mail content is: Please contact today12:30Attend the meeting in Conference Room 2...  

Posted by sell-traffic on Thu, 20 Jun 2019 14:01:13 -0700