This is the first one of Clone technology introduction. This article mainly introduces the basic knowledge of the object Clone technology.
Clone Basic Knowledge Reserve
In Java mentioned Clone technology, you can't mention the java.lang.cloneable interface and an Object class containing the Clone method. All classes with Clone features have a characteristic that it implements a Cloneable interface directly or indirectly. Otherwise, we will trigger the ClonyNotSupportedException exception when trying to call the Clone () method. Below we discover and understand this feature by analyzing partial source code of the Object class. Please see the source code of the Object # clone () method in the JDK:
/ *
..........
* @Return a clone of this instance. * @Exception? CloneNotSupportedException? If the object's class does not * support the Cloneable interface. Subclasses * that override the clone method can also * throw this exception to indicate that an instance can not * be cloned. * @see java.lang.cloneable * /
Protected Native Object Clone () throws clonenotsupportedException;
The description of this source of the @Exception section confirms the correctness of the discrimination of Clone object characteristics above. It expresses that the object class must support the Cloneable interface, otherwise even if the derived class covers the Object # clone () method, it will also throw this exception. With regard to overriding clone () methods, subsequent articles will be more detailed in detail using specialty.
In the previous one, the basic knowledge of Clone in Java is introduced. This article will focus on how to implement Clone.
l Clone implementation
1. Implement a Cloneable interface
Through the introduction of the previous article, we know that a class must have a Cloneable interface. To do this, Clone features have been basically achieved. Clone features For us, the most important thing is to be able to use it. So how can we use the clone function? The answer is to override the Object # clone () method.
2. Override Object # clone () method
Why do you need to override the Object # clone () method? It has to stand again from the JDK source code again. The prototype of the Object # clone () method in the JDK is:
Protected Native Object Clone () throws clonenotsupportedException;
Whether to note that here the clone () method modifier is protected instead of public. The invisibility of this access makes us not visible to the Object # clone () method. I believe that readers have understood why the object # clone () method is to overwrite. Moreover, the modifier of the covered method must be a public, and if it is still reserved as protected, the overlay will become no practical. Let's take a simple example of a Clone function:
/ *
* Examples of classes with Clone features
* /
Public Class CloneableObjexample Implements Cloneable {
// ... part of the code has omitted ...
Private string name = NULL;
Private int score = 0; / **
* Note: Change the protected modifier to public
* @see java.lang.Object # clone ()
* /
Public / * protected * / Object Clone () throws clonenotsupportedException {
// Call method of the parent class
Object result = super.clone ();
// Todo: Custom Clone data
Return Result;
}
}
3. Customize Clone
At this point, Clone has truthfully white. Clone objects we can customize it. Also on the example above. The following method has been enhanced to the function:
Public / * protected * / Object Clone () throws clonenotsupportedException {
// Call method of the parent class
CloneableObjexample Result = (CloneableObjexample) super.clone ();
// Todo: Custom Clone data
// Although "Clone" is, you can also do point adjustments
Result.name = "new name";
Result.score = 90;
Return Result;
}
This article introduces how to implement Clone. The next parameters will analyze the advanced features of Clone, etc. Clone, etc.
This chapter will enter the advanced characteristics of Clone, focusing on depth Clone technology. Clone usually has two types of shallow Clone and deep clone. First, analyze the differences in two. Shallow Clone and Deep Clone are Clone, which essentially defines whether the subject's property (non-primary type attribute, such as INT, etc.) is derived at Clone. If it is still reserved as a reference, it is called shallow Clone, which is called a deep clone. In fact, these two concepts are also relative concepts. They have a bit different from them, and the shallow clone mode is a Clone object. After getting the Clone object, "Clone" is required to "Clone" processing on the referenced member properties. From this level, the deep clone does not have a special difficulty. Simple talk is to create a good object and set some member properties. About deep clone, there are too many articles on the Internet, and it is a bit of a bitter feeling. This article is no longer described. This is not the focus of this article. The focus of this article is to explain the depth clone, that is, "N Deep Clone". What exactly? The goal described herein is to have been deep to the extent you want, including deeper deeper. Implementation is combined with Java Reflection technology and recursive. The approximate step is as follows: First, Java Reflection technology is used to dynamically obtain a list of members. Then via the depth of Clone, the members with Clone conditions and the necessary Clone are also clone. This is a recursive process until the Clolne depth has until the object does not require Clone's member properties. What is a member of Clone condition and a member of the necessary Clone? For example, the primitive type, the type of transient, is not accessible (! Field # isaccessible ()), does not implement the type of the Cloneable interface, etc., there is no Clone condition. The type of Java definition such as String does not need to go deep into Clone, which belongs to unnecessary clone. But the "container" class such as the List type is a member type of the clone. According to this, the recursive program is illustrated as follows: / ** * @Return Object Return to the object * @Param obj original object * @Param Length Clone depth * / public object DeepClone (Object Object Deepclone " {Object Result = Obj; // This is pseudo code: If the object OBJ does not have a Clone condition, return Result, which is also the recursive end condition. / / Here is pseudo code: If the object OBJ is not necessary, returns Result
// This is pseudo code: Start "Clone" object. This place is to adjust an abstract method to add a lot of flexibility. This method is the main purpose to implement the "clone" object scheme. Note: The "Clone" program in this may be what we want to think of, it may have a lot of ideas, but the effect is the same, it is to "clone" new object. Of course, it is the most easy thinking that the Object # clone () method is. Drawing is as follows:
Result = om.clone (OBJ);
// Here is pseudo code: all members who have a Clone condition and the necessary Clone are available. This place is also an abstract method to handle it. It is also to enhance flexibility. There are many ways to get these members, which may be obtained by setter and getter pairs, or by get Fields, etc. (this method may be many members can be directly accessible, often need to be combined with other methods), Even a combination of a variety of methods. In short, the purpose is only one, that is, these members are obtained. For (int i = 0; i / / Treatment // If you have no need to judge the member, then in addition to the "container" member, it has also ended over IF (Length <= 1) { IF (! "" container "member) { CONTINUE; } Try { // Just clon once, pay attention to the depth parameters of the recursive method CloneDfieldValue = DeepClone ("Container" member, 1); } catch (exception ex2) { EX2.PRINTSTACKTRACE (); Return Result; } } else { Try { CloneDfieldValue = DeepClone (member of member, Length - 1); } catch (exception ex) { EX.PrintStackTrace (); Return Result; } } Try { / / Here is pseudo code: set the clone's good value (CloneDfieldValue) } catch (exception ex) { EX.PrintStackTrace (); Return Result; } } // for .. Return Result; } At this point, "N Deep Clone" has been completed. Let's discuss other related issues. For example, this depth Clone is originally a-> b -> c - ... -> XZ, that is, Class A contains B members, and the B is also included in C member, and so on. If you want to "N Deep Clone", what is the member of the clone "XZ"? In fact, it is very simple. This problem is mainly to solve some members in the recursive process. Some members do not need clone to still reserve the quote. In the above recursion example, it has been mentioned that "the" clone "" scheme "has been defined as an abstract method, then we only need to make this method to meet this demand implementation.