In-depth java clone technology

xiaoxiao2021-03-06  37

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 Realization 1. Implement the CLoneable interface through the previous introduction, we know that a class must implement 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 is: protected native object clone () throws clonenotsupportedException; not noted 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. The following is a simple example of a Clone function: / * * Example of classes with clone features * / public class cloneableObjexample Implements cloneable {// ... some code has omitted ... private string name = null; private int score = 0 ;

/ ** * Note: Change protected modifier to public * @see java.lang.object # clone () * / public / * protected * / Object Clone () throws clonenotsupportedException {// call parent class Clone method Object Result = super.clone ();

// Todo: Custom Clone Data Return Result;}} 3. Custom Clone to this, Clone has truthfully. Clone objects we can customize it. Also on the example above. The following method has a certain enhancement to the function: public / * protected * / Object Clone () throws clonenotsupportedException {// call parent class CloneableObjexample Result = (CloneableObjexample) super.clone ();

// Todo: Custom Clone data // though "clone", but you can also adjust the 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. The schematic is as follows: result = om.clone (obj); // is pseudo code: Get all members of the Clone condition and the necessary clone. 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

// If you have no need to judge the member, in addition to the "container" member, the clone ends IF (Length <= 1) {if (! "" Container "member) {Continue;} try {// only clone once Note that the depth parameters of the recursive method are incoming 1 clonedfieldValue = DeepClone ("container" member, 1);} catch (exception ex2) {ex2.printstackTrace (); returnrate;}} else {Try {clonedfieldValue = DeepClone (Value, Length - 1);} catCH (Exception ex) {ex.printstackTrace (); returnrating;}} try {// This is pseudo code: Set the CLONEDFIELDVALUE to} catch (Exception ex) {ex.printStackTrace (); return result;}} // for .. Return Result;}

转载请注明原文地址:https://www.9cbs.com/read-67769.html

New Post(0)