Why cloning is required
In the actual programming process, we often encounter this situation: there is an object A, in a moment a is already included in a number of valid values, it may be necessary to a exactly the same new object B, and then any changes to B will not affect the value of a, that is, A and B is two separate objects, But the initial value of B is determined by the A object. In the Java language, the use of simple assignment statements is not sufficient to meet this demand, there are many ways to meet this demand.
how clones are implemented
first, shallow cloning
Shallow clone for the object to be cloned, for the properties of its base data type, copy one copy to the newly generated object, and for a property of a non-basic data type, just copy a reference to the newly created object. That is, both the newly generated object and the properties of the non-basic data type in the original object point to the same object.
shallow cloning steps:
1. Implement Java.lang.Cloneable interfaceWhy should the class of clone implement the Cloneable interface? The Cloneable interface is an identity interface and does not contain any methods! This identifier is only for the Clone () method in the object class if the Clone class does not implement the Cloneable interface and invokes the Clone () method of object (that is, super is called. Clone () method, the Clone () method of object throws a Clonenotsupportedexception exception.
2. Rewrite the Java.lang.Object.clone () methodJdkapi's explanatory documentation explains that this method returns a copy of the object. There are two points to note: one is that the Copy object returns a new object, not a reference. Second, the difference between a copy object and a new object returned with the newly operator is that the copy already contains information about the original object, not the object's initial information.observing The Clone () method of the object class is a native method, and the efficiency of the native method is generally much higher than the non-native method in Java. This also explains why the clone () method in object is used instead of a new class, and then the information in the original object is assigned to the object, although this also implements the Clone function. Clone () in the object class is also a method of the protected property, which is overridden to set the properties of the Clone () method to public .
The Clone () method in the object class produces the same amount of space as the original object in memory, and then copies the contents of the original object as it is. There is no problem with basic data types, but for non-primitive type variables, we know that they hold only references to objects, which also causes the non-basic type variables after clone and the corresponding variables in the original object to point to the same object.
Java code example:public class Product implements cloneable {private String name; Public Object Clone () {try {returnsuper.clone (); } catch (Clonenotsupportedexception e) {returnnull; } } }
second, deep cloning
On the basis of a shallow clone, a class that corresponds to a property of a non-basic data type in the object to be cloned also implements cloning, which
for a property of a non-basic data type, the copy is not a reference, that is, the newly generated object and the property of the non-basic data type in the original object point to not the same object
deep cloning steps:class that corresponds to the properties of all non-basic data types in the class and class to be cloned 1, all implement Java.lang.Cloneable interface 2, both rewrite Java.lang.Object.clone () method
Java code example:public class Attribute implements cloneable { private String no; Public Object clone () { try {  &N Bsp Returnsuper.clone (); } catch (Clonenotsupportedexception e) { & nbsp Returnnull; } } } public Class Product implements cloneable { private String name; Private Attribute attribute; public Object clone () { try { Returnsuper.clone (); &n Bsp } catch (Clonenotsupportedexception e) { Returnnull; } } }
third, using object serialization and deserialization to achieve deep cloningThe so-called object serialization is to convert the state of an object into a byte stream, which can then be used to generate objects of the same state. The serialization of objects and another feature that is easily overlooked is Object replication (clone), where most objects can be copied through the clone mechanism, but it is well known that clone has deep clone and shallow clone, if your object is very, very complex, and want to implement deep clone, if using serialization, no more than 10 lines of code can be solved.Although the serialization of Java is very simple and powerful, there are a lot of places to be aware of. For example, once serialized an object, but for some reason, the class made a little change, and then re-compiled, then the object is deserialized just now, there will be an exception. You can solve this problem by adding the Serialversionuid property (inJava serialization and deserialization Learning (ii): This description is described in heading three of the serialization interface description).
if your class is a singleton (Singleton) class, although we have concurrency problems under multithreading to control the singleton, whether the user is allowed to replicate the class through a serialization mechanism or a clone, If you do not allow you to be cautious about the implementation of this class (Let this class not implement the Serializable interface or the Externalizable interface and
Cloneable Interface
on the line).
Java code example:Public ClassAttribute {private String no; } public Classproduct {private String name; Private Attribute Attribute; Public Product Clone () {Bytearrayoutputstream byteout = null; ObjectOutputStream objout = null; Bytearrayinputstream Bytein = null; ObjectInputStream Objin = null; try {//Serializes the object into a stream, because a copy of the object is written in the stream, and the original object still exists inside the JVM. So the deep copy of the object can be realized by using this feature. byteout =new bytearrayoutputstream (); objout =new ObjectOutputStream (byteout); objout.writeobject (this); //serializes a stream into an object Bytein =new Bytearrayinputstream (Byteout.tobytearray ()); & nbsp Objin =new ObjectInputStream (bytein); & nbsp return (Contreteprototype) objin.readobject (); catch (IOException e) { throw newruntimeexception ("Clo Ne Object failed in IO. ", e); } catch (ClassNotFoundException e) {   ; throw newruntimeexception ("Class not found.", e); finally{ try{ Bytein = null; &N Bsp Byteout = null; if (objout! = null) objout.close (); if (Objin! = null) objin.close (); }catch (IOException e) { } } } }&nbs p;
######################## #注意 ######################several of the frameworks in which Bean replication (apachebeanutils, propertyutils,spring beanutils,cglibbeancopier) are equivalent to shallow clones in clones. 1) Spring package and beanutils in Apache are implemented using reflection Spring:voidcopyproperties (Object source, Object target,string[]ignoreproperties)apache:void copyproperties (Object dest, Objectorig)2) The Beancopier in the Cglib package is implemented with dynamic byte code Cglib:beancopiercreate (class source, class Target,booleanuseconverter) For example:beancopier copier=beancopier.create (Stusource.getclass (), Stutarget.getclass (), false);Copier.copy (stusource,stutarget, NULL);The following performance analysis was done on the use of bean attribute replication within the company:
cglib beancopier 15ms
Spring beanutil 4031ms
Apache beanutils 18514ms.
Shallow cloning and deep cloning of Java objects