Simple Java Clone technology

Source: Internet
Author: User
Tags abstract contains implement interface reference reflection return string
This is the first of the introduction to clone technology. This article mainly introduces the basic knowledge of object clone technology.

Clone Basic Knowledge Reserve
In Java, mention of the clone technology, you must mention the Java.lang.Cloneable interface and contains the Clone method of the object class. All classes that have a clone feature have an attribute, that is, it implements the Cloneable interface directly or indirectly. Otherwise, when we try to invoke the Clone () method, the clonenotsupportedexception exception is triggered. Here we find and understand this feature by analyzing some of the source code of the object class. Please see the source code for 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 the instance cannot
*be cloned.
* @see java.lang.Cloneable
*/


Protected native Object clone () throws Clonenotsupportedexception;



The description of the @exception section of the source code confirms the correctness of the assertions about the characteristics of the clone object above. It explicitly states that the object class must support the Cloneable interface, or else it throws the clonenotsupportedexception exception even if the derived class overrides the Object#clone () method. With respect to covering the Clone () method, the subsequent articles will be analyzed in more detail in a specific space.


In the previous article, I introduced the basics of clone in Java. This article will focus on how to implement clone.





L Clone implementation

1. Implement Cloneable interface

By introducing the previous article, we know that a class must implement the Cloneable interface if it is to have a clone function. To do this, the clone function has been basically implemented. Clone function for us, the most important thing is to be able to use it. So how can we use the clone feature? The answer is to overwrite the Object#clone () method.

2. Overlay Object#clone () method

Why do I need to overwrite the Object#clone () method? Here again, from the JDK source code. The prototype of the object# Clone () method in the JDK is:

Protected native Object clone () throws Clonenotsupportedexception;

Did you notice that the Clone () method modifier here is protected, not public. The invisibility of this access makes us invisible to the Object#clone () method. It is believed that the reader has understood why the Object#clone () method should be overwritten. Also, the modifiers of the overridden method must be public, and if you leave it as protected, the overlay will become meaningless. Here's a simple example with the clone feature:

/*

* Example of a class with a clone function

*/

public class Cloneableobjexample implements cloneable {

...... Some of the code has been 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 {

The Clone method of the Call parent class

Object result = Super.clone ();



TODO: Customizing Clone data

return result;

}

}

3. Custom Clone

At this point, clone has been the truth. We can customize the object of the clone. As for the above example. The following methods make some enhancements to the functionality:

public/*protected*/Object Clone () throws Clonenotsupportedexception {

The Clone method of the Call parent class

Cloneableobjexample result = (cloneableobjexample) super.clone ();



TODO: Customizing Clone data

Although "clone", but can also do a little adjustment

Result.name = "New name";



Result.score = 90;

return result;

}





This article describes how to implement clone. The next space will be an analysis of the advanced features of clone, such as depth cloning.


This chapter will go into the advanced features of clone, highlighting the deep clone technology.

There are usually two types of clones, namely, Shallow clone and deep clone. First, analyze the difference between two kinds. Both shallow and deep clones are clones, which essentially distinguish between the member properties within an object (not native type attributes, such as int, and so on) that are processed as references at clone. If it is still a reference, it is called a shallow clone, whereas it is called deep clone. In fact, these two concepts are also relative concepts. In the processing they are a little different, shallow clone way to get the Clone object, deep clone way after get the clone object, also need to refer to the member properties of "clone" processing. From this level, deep clone is not particularly difficult, simply to create a good object, and then set some member properties. On the deep clone, online article already has too many, a little dizzying feeling, this article no longer repeat, this is not the focus of this article.

This article focuses on the elaboration of the deep clone, that is, "N Deeply clone". To what extent? The goal described in this article is to be as deep as you want, including the degree of depth that cannot be deeper.

The implementation scheme is combined with Java reflection technology and recursion.

The general steps are described as follows: first, using Java reflection technology to dynamically get the list of member methods. Then, depending on the depth of the clone, clone the members that have the clone condition and are required to clone. This is a recursive process until the clolne depth has been reached or until the object has no member properties that require clone.

What is a clone of a member who has a clone condition and is required to clone it? For example, the primitive type (primitive type), which is defined as a transient (Transient) type, cannot be accessed by a type (!). Field#isaccessible ()), do not implement the type of cloneable interface, etc., do not have clone conditions. Java-defined types such as string do not need to be further clone-these are cases where cloning is not necessary. However, the container class, such as the list type, is a member type that has the necessary clone.

Accordingly, the recursive program is indicated as follows (Deepclone is the Java method):

/**

* @return object to return the clone

* @param obj Original object

* @param length Clone depth

*/

public object Deepclone (object obj, int length) {

Object result = obj;

Pseudo code here: Returns result if object obj does not have a clone condition, which is also a recursive end condition.





Pseudo code: Returns result if object obj does not need to clone





Pseudo code here: Start the Clone object. This place is an abstract method to deal with, which can add a lot of flexibility. The main purpose of this method is to implement the "Clone" object scheme. Note: This "clone" scheme may be a plan we would not think of, it may have a lot of ideas, but the effect is the same, is to "clone" a new object out. Of course, the easiest thing to think about is the Object#clone () method. The signal is as follows:

result = Om.clone (obj);



Pseudocode here: Gets all members that have the clone condition and are required to clone. This place is also an abstract method to deal with. The same is to enhance flexibility. There are a number of ways to get these members, either by setter and getter pairs, or by getting fields and so on (this method may not be directly accessible to many members, often requiring a combination of other methods), or even a combination of multiple methods. In short, only one purpose is to obtain these members.





for (int i = 0; i < fields.length; i++) {

To process a member





If you no longer need to judge a member, then the clone ends in addition to the "container" member

if (length <= 1) {

if (!) Container "Member" {

Continue

}

try {

Just clone it once, note that the depth parameter of the recursive method passes in 1

Clonedfieldvalue = Deepclone (Value of the "container" member, 1);

catch (Exception ex2) {

Ex2.printstacktrace ();

return result;

}

} else {

try {

Clonedfieldvalue = Deepclone (value of member, LENGTH-1);

catch (Exception ex) {

Ex.printstacktrace ();

return result;

}

}

try {

Pseudo code here: Set the clone 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 some other related issues below. For example, this kind of depth clone was originally A-->b-->c--......-->xz, which means that Class A contains B members, B contains C members, and so on. If you want to "N Deep clone", only Clone "XZ" This member how to do? In fact, this problem is mainly to solve in the recursive process some members need to clone while some Members do not need to clone still retain the reference to this problem. As already mentioned in the recursive example above, the "scenario" for implementing "clone" has been defined as an abstract method, so we just need to do a implementation of this method to satisfy this requirement.




Related Article

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.