Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the properties of Java cloned objects

2025-02-25 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article introduces the relevant knowledge of "what are the characteristics of Java cloned objects?". In the operation of actual cases, many people will encounter such a dilemma. Then let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

In java object-oriented programming, to copy an object of a reference type, you must clone the object. Cloning is achieved by calling clone methods that are available to all reference types and objects.

In the thinking of passing values and extending deep cloning in Java, we have said that all objects extended to the cloning technology Java are subclasses of the Object class. We know that Java is a pure object-oriented programming language. In Java, the parent classes of all classes are java.lang.Object classes, that is, if a class does not show a declaration of inheritance, its parent class defaults to java.lang.Object.

There is a very simple way to prove this. Let's write a Test class, as follows:

Public class Test {public void someMethod () {super.clone ();}}

Super.clone () is called inside, and no error is reported at compile time. In fact, the clone () method is a protected method provided by the java.lang.Object class.

Object cloning

This article explains the object cloning features of Java language by introducing the java.lang.Object#clone () method.

The java.lang.Object#clone () method is implemented by java.lang.Object, which mainly clones the object itself.

First, let's take a look at the following example:

Public class TestClone {public static void main (String [] args) {MyClone myClone1 = new MyClone ("clone1"); MyClone myClone2 = (MyClone) myClone1.clone (); if (myClone2! = null) {System.out.println (myClone2.getName ()); System.out.println ("myClone2 equals myClone1:" + myClone2.equals (myClone1));} else {System.out.println ("Clone Not Supported");}} class MyClone {private String name Public MyClone (String name) {this.name = name;} public String getName () {return name;} public void setName (String name) {this.name = name;} public Object clone () {try {return super.clone ();} catch (CloneNotSupportedException e) {return null;}}

Compile and execute TestClone, printing out:

C:\ clone > javac * .java C:\ clone > java TestClone Clone Not Supported C:\ clone >

Indicates that the MyClone#clone () method throws a CloneNotSupportedException exception when calling super.clone (), and cloning is not supported.

Why is the clone () method provided in the parent class java.lang.Object but not called?

It turns out that although the Java language provides this method, but considering the security problem, on the one hand, the clone () access level is set to protecte type to restrict external class access.

On the other hand, it forces subclasses that need to provide clone functionality to implement the java.lang.Cloneable interface. At run time, JVM checks the class that calls the clone () method, and throws a CloneNotSupportedException exception if the class does not implement the java.lang.Cloneable interface.

The java.lang.Cloneable interface is an empty interface that does not declare any properties or methods. This interface simply tells JVM that the implementation class of the interface needs to open the "clone" function.

Let's change the MyClone class slightly to implement the Cloneable interface:

Class MyClone implements Cloneable {. / / other unchanged} compile and execute TestClone, and print out: C:\ clone > javac * .java C:\ clone > java TestClone clone1 myClone2 equals myClone1: false C:\ clone >

According to the results, we can find that:

1myClone1.Clone () cloned an object with the same attribute value as myClone1.

2, but the cloned object myClone2 and myClone1 are not the same object (with different memory space)

Summary

If you want a class A to provide cloning, the class must implement the java.lang.Cloneable interface and overload the java.lang.Object#clone () method.

Public class An extends Cloneable {public Object clone () {try {return super.clone ();} catch (CloneNotSupportedException e) {/ / throw (new InternalError (e.getMessage ()); return null;}

Deep-level cloning of objects

The above example shows how to clone an object with simple properties (String,int,boolean, etc.).

But if the property type of an object is List,Map, or other user-defined classes, how does the cloning behavior occur?

In many cases, we hope that even if the property value of the cloned object is modified, it will not affect the original object. This kind of cloning is called deep-level cloning of the object. How to achieve deep cloning of objects?

Verify how objects are cloned

To verify how objects are cloned, we improve the above example as follows (to save space, we omitted the setter and getter methods):

Public class TestClone {public static void main (String [] args) {/ / set values for cloned objects MyClone myClone1 = new MyClone ("clone1"); myClone1.setBoolValue (true); myClone1.setIntValue (100); / / set list values List listValue = new ArrayList (); listValue.add (new Element ("ListElement1")); listValue.add (new Element ("ListElement2")); listValue.add (new Element ("ListElement3")); myClone1.setListValue (listValue) / / set element value Element element1 = new Element ("element1"); myClone1.setElement (element1); / / Clone MyClone myClone2 = (MyClone) myClone1.clone (); if (myClone2! = null) {/ / simple attribute System.out.println ("myClone2.name=" + myClone2.getName () + "myClone2.boolValue=" + myClone2.isBoolValue () + "myClone2.intValue=" + myClone2.getIntValue ()) / / compound attributes (List and Element) List clonedList = myClone2.getListValue (); Element element2 = myClone2.getElement (); System.out.println ("myClone2.listValue.size ():" + clonedList.size ()); System.out.println ("myClone2.element.equals (myClone1.element):" + element2.equals (element1)); System.out.println ("myClone2.element.name:" + element2.getName ()) / / Let's test whether myClone2.element is equal to myClone1.element / / and whether myClone2.listValue is equal to myClone1.listValue / / for this reason, we modify myClone2.element and myClone2.listValue. If the corresponding values of myClone1 are also modified, they refer to variables in the same memory space, and we think they are equal to clonedList.add ("ListElement4"); System.out.println ("myClone1.listValue.size ():" + listValue.size ()). Element2.setName ("Element2"); System.out.println ("myClone1.element.name:" + element1.getName ());} else {System.out.println ("Clone Not Supported");} class MyClone implements Cloneable {private int intValue; private boolean boolValue; private String name; private List listValue; private Element element; public MyClone (String name) {this.name = name }. / / setter and getter methods} class Element implements Cloneable {private String name; public Element (String name) {this.name = name;}. / / setter and getter methods (abbreviated)}

Compile and execute TestClone, printing out:

C:\ clone > javac * .java C:\ clone > java TestClone myClone2.name=clone1 myClone2.boolValue=true myClone2.intValue=100 myClone2.listValue.size (): 3 myClone2.element.equals (myClone1.element): true myClone2.element.name:element1 myClone1.listValue.size (): 4 myClone1.element.name:Element2 09.myClone2 equals myClone1: false 10.C:\ clone > 11.

We find that super.clone () simply assigns values to compound attributes such as List,Element in the object, without cloning. In other words, changing the value of the object after being crowned will affect the original object.

How to do deep cloning?

The answer is that we can only clone the properties manually in the overloaded clone () method. Of course, the condition is that the attribute class also supports cloning operations.

Class MyClone implements Cloneable {... Public Object clone () {try {MyClone myClone = (MyClone) super.clone (); / / Clone the attribute respectively myClone.element = this.element.clone (); myClone.listValue = new ArrayList (); for (Element ele:this.listValue) {myClone.listValue.add (ele.clone ());} return myClone;} catch (CloneNotSupportedException e) {return null }}.} / / Let the Element class also support the clone operation class Element implements Cloneable {. Public Element clone () {try {return (Element) super.clone ();} catch (CloneNotSupportedException e) {return null;}

Deep-level cloning operations often have efficiency problems, especially when it is necessary for collection classes such as List,Map to support deep-level cloning operations.

This is the end of the content of "what are the characteristics of Java cloned objects". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report