Using reflection for deep cloning

Source: Internet
Author: User
Tags serialization shallow copy

As we all know, there are two better ways to replicate a counterpart, one is serialization, the other is cloning. It is convenient to use serialization for replication, because it is automated for deep replication, and only requires that the class that corresponds to the object that we are serializing implement the serialized markup interface serializable, which copies the other objects referenced in the object. But this efficiency is less efficient than the clone cloning method in object. Cloning with clone, however, is a shallow copy, and it does not automatically clone other objects referenced in the object, so if we want to make a deep copy, we need to overwrite the Clone method in the object and separate the fields that need to be deeply replicated, so it is more troublesome to apply them. It is because of this cumbersome, I used the reflection of the way to the deep cloning clone, the only need to clone the class to inherit the class Deepclone can be. For detailed procedures, see comments.

deep cloning implementation: Java code   /**   *    *  deep cloning with reflection, as long as the beans inheriting the class have the ability to deep cloning.    *    *  But it does not support the cloning of attribute members of parent classes because  this.getclass (). Getdeclaredfields ()    *   can only get property members that are all defined by itself, so this inheritance does not support the attribute members of the parent class    *  degree clones unless this reflection is discarded, and the Clone method is overridden for each bean.    *    *  Also note that this program is only for the implementation of the Cloneable interface and write the Clone method of the class instance before the    *  deep cloning, If your class contains reference types that do not implement cloneable interfaces, it will not help you with deep cloning    *  (although you can do it, such as by using serialization and deserialization to create another instance, but this violates the most    * of this class.   At the beginning of the design  --  it itself is an immutable class or is not a state of the tool class, then create a number of such    *  instances of no benefit, but will occupy memory and frequent call garbage back If the class is mutable and does not have a    *  implementation cloning interface, then this is a design error for the designer itself, so this will not help you clone these classes.    *    *  Remember that cloning does not make sense for beans of variable value class types, for immutable classes or for class object clones that do not have state    * . The immutable value type classes in the Java library are handled in this way, such as String, basic    *  type wrapper class, BigInteger ..., none of them have cloning capabilities    *    *  @author  jiangzhengjun 2010.5.5  &NBSP;*/&NBsp;  public abstract class deepclone implements cloneable, serializable  {          protected object clone ()  throws  clonenotsupportedexception {           Object  cloneobj = null;           try {               //  Cloning Objects                 cloneobj = super.clone ();                  //  All properties of the class, including static properties                field[] filedarr  = this.getclass () getdeclaredfields ();                field field;//Properties                class  fieldtype;//Property Type                 object filedval;//Property Value                 for  (int i = 0; i < filedarr.length; i++)  {                    field =  filedarr[i];                    fieldtype = field.gettype ();                    field.setaccessible (true);                    filedval = field.get (this);                    /*                    The following code runs results that indicate that Super.clone () is just a shallow copy, and it simply adds the original object                     Domain member memory address is copied to the cloned object, so if it is a reference type, point to the same object,                    if the underlying type is true, the stored value is copied directly into the Clone object, and the base type domain member does not need                    copy processing separately. However, the reference type is a line copy, so we need a reference type separate                     do special replication processing, that is, deep cloning.                                      below is the output of some time, The results from the output can confirm the above conclusion: &Nbsp;                    &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;I&NBSP;:  -1 - -1                   ca : CloneA@480457 - CloneA@480457                   ca1 : CloneA@47858e -  clonea@47858e                   ca2 : CloneA@19134f4 - CloneA@19134f4                   cb : CloneB@df6ccd -  cloneb@df6ccd                   sb :  -                    intarr : [[[i@601bb1 - [[[i@601bb1                   caarr : [[[lclonea;@1ea2dfe - [[[lclonea;@ 1ea2dfe                   cbarr : [[[lcloneb;@17182c1 - [[[lcloneb;@17182c1                   int1arr : [i@13f5d07 - [ i@13f5d07                   ca1Arr : [LCloneA; @f4a24a  - [LCloneA; @f4a24a                    cb1Arr : [LCloneB; @cac268  -  [LCloneB; @cac268                   */                   //Field  Clfiled = cloneobj.getclass (). Getdeclaredfield (                    //       Field.getname ());                    //clfiled.setaccessible (true);                    //system.out.println (Field.getname ()  +  "&NBSP;:   " + filedVal + "  -  "                    //      + clfiled.get (Cloneobj));     &Nbsp;      &nbs

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.