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

The method of JAVA object creation and object cloning

2025-01-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article mainly introduces the method of JAVA object creation and object cloning related knowledge, the content is detailed and easy to understand, the operation is simple and fast, has a certain reference value, I believe that everyone after reading this JAVA object creation and object cloning method article will have a harvest, let's take a look at it.

I. four ways to create an object

New creation

Reflection

Clone

Deserialization

Second, create objects through new

In general, when an object is created by the new keyword, it will first allocate space to the object on the heap, and then execute the constructor to perform a series of initialization to assign values to a number of attributes on the allocated memory space; after initialization, the reference of the heap object will be passed to the stack area, and finally participate in the running of the program.

III. Reflection

Call the newInstance () instance method of the Java.lang.Class or java.lang.reflect.Constructor class.

IV. Cloning objects

It is divided into deep copy and shallow copy, and the object is cloned (copied) by calling the clone method of the object.

We can see the definition of the clone method:

First of all, it is a native method

It is modified by protected, so its access rights are only its subclasses or [same package: java.lang.*]

Although classes inherit from Object, when object A references object BMaga, it cannot be called: B.clone () {B-> Object.clone ()}, because the clone () method on Object is modified by protected.

If A must access B's clone () method: B rewrites clone () to public modification, or passes clone () access through the public method.

In addition, we also need to implement: Cloneable interface, we can look at its definition, actually nothing, we can think of Cloneable as a tag, if we do not implement it, we will throw an exception when we call the rewritten clone method to clone: [java.lang.CloneNotSupportedException]

Clone does not call the constructor of the class, it just copies the object information on the heap area.

To test clone, I defined two classes:

User Information: UserBean

Package com.bokerr.canaltask.po;import lombok.AllArgsConstructor;import lombok.Data;import java.io.Serializable;@Data@AllArgsConstructorpublic class UserBean implements Cloneable, Serializable {private static final long serialVersionUID = 2022010901L; / * * basic type, immutable type * / private int age; private int sex; private String name; private String home; / * * reference type * / private SubInfo subInfo Public UserBean () {} / * rewrite clone to public so that any object has access to clone * * / @ Override public UserBean clone () {UserBean clone = null; try {clone = (UserBean) super.clone ();} catch (CloneNotSupportedException e) {e.printStackTrace ();} return clone;}}

Additional information class: SubInfo

Package com.bokerr.canaltask.po;import lombok.AllArgsConstructor;import lombok.Data;import java.io.Serializable;@Data@AllArgsConstructorpublic class SubInfo implements Cloneable, Serializable {private static final long serialVersionUID = 2022010902L; / * the attributes of the SubInfo class are all basic types, immutable objects (String) * * / private String work; private Integer salary; private int idNum Public SubInfo () {} / * here provides object clone method access through the public method * * / public SubInfo selfClone () {try {return (SubInfo) clone ();} catch (CloneNotSupportedException e) {e.printStackTrace ();} return null } / * @ Override public SubInfo clone () {try {return (SubInfo) super.clone ();} catch (CloneNotSupportedException e) {e.printStackTrace ();} return null;} * /} shallow copy

We need to know that simply calling the clone method of an object, it carries out: "shallow copy", when the properties of the object are basic type or immutable (final) type, there is no problem; but when there is a variable object reference, the copy of it is not a deep copy, it only copies the reference of the object, so that the modification of the original object and the cloned object will be reflected on the reference object.

For a shallow copy, take a look at the following test code:

Package com.bokerr.canaltask.workerrun;import com.bokerr.canaltask.po.SubInfo;import com.bokerr.canaltask.po.UserBean;public class ExecuteTest {public static void main (String [] args) {UserBean userBean1 = new UserBean (); userBean1.setAge (25); userBean1.setSex (1); userBean1.setName ("bokerr"); userBean1.setHome ("Guizhou Tongren"); SubInfo subInfo1 = new SubInfo () SubInfo1.setIdNum (3423); subInfo1.setSalary (Integer.valueOf (15000)); subInfo1.setWork ("coder"); userBean1.setSubInfo (subInfo1); System.out.println ("userBean-orign:" + userBean1); UserBean userBean2 = userBean1.clone (); userBean2.setHome ("Guizhou Guiyang"); userBean2.setAge (26); SubInfo subInfo2 = userBean2.getSubInfo () SubInfo2.setSalary (Integer.valueOf (25000)); subInfo2.setWork ("manager"); subInfo2.setIdNum (100002); System.out.println ("# #"); System.out.println ("userBean-orign:" + userBean1); System.out.println ("userBean-clone:" + userBean2);}}

The clone method of UserBean is defined as follows. We can see that it only calls super.clone without making any changes to the return value of super.clone:

Override public UserBean clone () {UserBean clone = null; try {clone = (UserBean) super.clone ();} catch (CloneNotSupportedException e) {e.printStackTrace ();} return clone;}

The output is as follows. Combined with the test code, we can find that the modification of the cloned object to SubInfo is also reflected in the SubInfo object referenced by the original object, because calling super.clone is only a "shallow copy".

UserBean-orign:UserBean (age=25, sex=1, name=bokerr, home= Guizhou Tongren, subInfo=SubInfo (work=coder, salary=15000, idNum=3423)) # # userBean-orign:UserBean (age=25, sex=1, name=bokerr, home= Guizhou Tongren, subInfo=SubInfo (work=manager, salary=25000, idNum=100002) userBean-clone:UserBean (age=26, sex=1, name=bokerr, home= Guizhou Guiyang, subInfo=SubInfo (work=manager, salary=25000, idNum=100002)) Deep copy

The object generated by deep copy must have completely independent object memory space, and the modifications on the copy object and the original object will not affect each other.

As mentioned earlier, calling the clone method on Object through super.clone is actually a shallow copy.

In order to make a deep copy, we must modify the clone method of UserBean:

/ * rewrite clone to public so that any object has access to clone * * / @ Override public UserBean clone () {UserBean clone = null; try {clone = (UserBean) super.clone () / * * SubInfo.selfClone () provides SubInfo object clone () method permission * / / * * Clone variable reference object SubInfo and assign it to the returned value of super.clone (): UserBean completes deep copy * / SubInfo cloneSub = this.subInfo.selfClone (); clone.setSubInfo (cloneSub);} catch (CloneNotSupportedException e) {e.printStackTrace () } return clone;}

In fact, other than that, the test code remains the same, and then we look at the output now, and we can see that the modification to the reference object of the cloned object, SubInfo, does not change the SubInfo of the original object.

UserBean-orign:UserBean (age=25, sex=1, name=bokerr, home= Guizhou Tongren, subInfo=SubInfo (work=coder, salary=15000, idNum=3423)) # # userBean-orign:UserBean (age=25, sex=1, name=bokerr, home= Guizhou Tongren, subInfo=SubInfo (work=coder, salary=15000, idNum=3423) userBean-clone:UserBean (age=26, sex=1, name=bokerr, home= Guizhou Guiyang, subInfo=SubInfo (work=manager, salary=25000, idNum=100002))

Here comes the question: what if my object is referenced at multiple levels and multiple objects are referenced? Do I have to rewrite the clone method one by one?

Yes, if you use the clone method, you really need to deal with it that way.

Suppose that the following reference relationship exists with object An as the root node:

A-> BC-> E-> FG-> GD-> HI-> J-> K

I'm sure people who deal with deep copies will go crazy.

So is there a more convenient way? Of course, that's the deserialization mentioned in the next section.

5. Deserialization

Serialization in java converts an object into a sequence of binary bytes that can be persisted to a disk file or transferred over a network.

Deserialization refers to the process of restoring the binary byte sequence to an object and loading it into memory.

During the deserialization of the object, no constructor is called, and the whole object is obtained by recovering the data obtained from the file stream.

Serialization saves only the property state of the object, not the object's methods.

Only classes that implement the Serializable interface can be serialized. It is officially recommended to customize a SerialversionUID. If the user does not have a custom SerialversionUID, the default value will be generated. Serialization and deserialization are carried out by comparing their SerialversionUID. Once the SerialversionUID does not match, deserialization will not be successful.

If the property of a class contains an object reference, the referenced object will also be serialized. [the referenced object must also implement the Serializable interface, otherwise an exception will be thrown: java.io.NotSerializableException]

Variables modified by static and transient will not be serialized, which can be understood as: static is a class property that exists in the method area rather than in the heap area; transient is often used to modify security-related information, and it can only be used with the Serializable interface, such as user password, which should not be serialized and transmitted on the network.

Reference Code:

Package com.bokerr.canaltask.workerrun;import com.bokerr.canaltask.po.NoCloneInfo;import com.bokerr.canaltask.po.SubInfo;import com.bokerr.canaltask.po.UserBean;import org.apache.commons.lang3.SerializationUtils;import java.util.Arrays;public class ExecuteTest {public static void main (String [] args) {UserBean userBean1 = new UserBean (); userBean1.setAge (25); userBean1.setSex (1); userBean1.setName ("bokerr") UserBean1.setHome (Guizhou Tongren); SubInfo subInfo1 = new SubInfo (); subInfo1.setIdNum (3423); subInfo1.setSalary (Integer.valueOf (15000)); subInfo1.setWork ("coder"); userBean1.setSubInfo (subInfo1); System.out.println ("before serialization" + userBean1) / * * objects are serialized into binary byte sequences * / byte [] serializeBytes = SerializationUtils.serialize (userBean1); / * * deserialization is restored to Java objects * / UserBean userBeanSer = SerializationUtils.deserialize (serializeBytes); userBeanSer.getSubInfo (). SetSalary (800000); userBeanSer.getSubInfo (). SetWork ("CTO"); System.out.println ("deserialization" + userBeanSer) System.out.println (userBean1 = = userBeanSer);}}

Output:

Pre-serialization UserBean (age=25, sex=1, name=bokerr, home= Guizhou Tongren, subInfo=SubInfo (work=coder, salary=15000, idNum=3423))

Deserialize UserBean (age=25, sex=1, name=bokerr, home= Guizhou Tongren, subInfo=SubInfo (work=CTO, salary=800000, idNum=3423))

False

We can find that the final output: subInfo.work=CTO subInfo.salary=800000, the modification of the SubInfo object referenced by the deserialized object does not affect the original object, so we can make a deep copy of the object through deserialization.

VI. Supplement

PS* has one thing to say: lombok is really easy to use. Although set and get methods can be generated automatically, the code is obviously more concise after using lombok.

Commons-lang3 is a toolkit for apache, and the serialization tool I use comes from it.

Maybe some of my friends don't understand, so I'd better post Maven dependence, although I know everyone is the boss per capita.

Org.projectlombok lombok true compile org.apache.commons commons-lang3 3.12.0 this is the end of the article on "methods of JAVA object creation and object cloning". Thank you for reading! I believe you all have a certain understanding of the "methods of JAVA object creation and object cloning". If you want to learn more, you are welcome to follow the industry information channel.

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