Java-deep Clone

Source: Internet
Author: User
Tags modifiers shallow copy

Let me first describe the problem:
I wrote a function p in the action (struts2.x)-A, with one of the current user's identity F = = 1 o'clock need to go this function, and this function for some reason has penetrated into some other method.
By the way, the method that obtains the current user session in a is already encapsulated by the parent class.
Then my code was already on the push, and the next day I was told if I could get rid of this feature for the time being.
It's too much trouble to comment out.
So I decided to override in this a to get the method of the current user session and assign F to 0.

So I just need to have a shallow copy on it.
For example, I can do this:
Give the user a implements Clonable.
Then, in the override of GetUserInfo (), clone one out and then assign the value setf (0)

But this may not be very good, after all, I need to move user.
I can use org.springframework.beans.BeanUtils.copyPropergties directly (Source,target)
Look at the source code, inside is SOURCEPD is also targetpd,pd is what?


Just use it as a medium for describing Java beans.
Of course, he is also shallow copy ...

 for(PropertyDescriptor Targetpd:targetpds) {if(Targetpd.getwritemethod ()! =NULL&&(Ignoreproperties==NULL|| (!Ignorelist.contains (Targetpd.getname ())))) {PropertyDescriptor SOURCEPD=Getpropertydescriptor (Source.getclass (), Targetpd.getname ()); if(SOURCEPD! =NULL&& Sourcepd.getreadmethod ()! =NULL) {Try{Method Readmethod=Sourcepd.getreadmethod (); if(!Modifier.ispublic (Readmethod.getdeclaringclass (). getmodifiers ())) {readmethod.setaccessible (true); } Object Value=Readmethod.invoke (source); Method Writemethod=Targetpd.getwritemethod (); if(!Modifier.ispublic (Writemethod.getdeclaringclass (). getmodifiers ())) {writemethod.setaccessible (true);      } writemethod.invoke (target, value); } Catch(Throwable ex) {Throw NewFatalbeanexception ("Could not copy properties from source to target", ex); } }}}

Anyway, this has solved my problem, a call GetUserInfo () is my clone user, does not affect the other action.

But what if I tag that day with a field of a simple type with a reference type of user?
Then I have to deep clone, usually mastered the class library is not much, let me solve the words I how to do?

Maybe I can do this:

New File ("@#$%^&*"new objectoutputstream (new  FileOutputStream (f)); Oos.writeobject (u0);

ObjectInputStream ois = new ObjectInputStream (new FileInputStream (f));
u1 = (User) ois.readobject ();

It's a simple and rude way to look at a small piece of code, but I'm going to have to use the user and the reference type Plus implements Serializable ...

Then I found something like this:

<dependencies>    <dependency>        <groupId>uk.com.robust-it</groupId>        < artifactid>cloning</artifactid>        <version>1.9.0</version>    </dependency></ Dependencies>

This can be used:

New= cloner.deepclone (u0); U1.getpet (). SetName ("Papapa"); System.out.println (u0); System.out.println (U1);

The result is that the name of the U1 pet after clone becomes Papapa and there is no change in the u0 as clone source, which is deep clone.

Ignoring the case that clone source is an array, the key part of this class for Deep clone is as follows:

 for(FinalField Field:fields) {Final intmodifiers =field.getmodifiers (); if(!modifier.isstatic (modifiers)) {if(Nulltransient &&modifier.istransient (modifiers)) {//request by Jonathan:transient fields can be null-ed        Finalclass<?> type =Field.gettype (); if(!type.isprimitive ()) {Field.set (newinstance,NULL); }}Else{FinalObject Fieldobject =Field.get (o); Final BooleanShouldclone = (Clonesynthetics | | (!clonesynthetics &&!field.issynthetic ())) && (Cloneanonymousparent | | ((!cloneanonymou sparent &&!)isanonymousparent (field))); FinalObject Fieldobjectclone = clones! =NULL? (Shouldclone?)cloneinternal (Fieldobject, clones): Fieldobject): Fieldobject;      Field.set (newinstance, Fieldobjectclone); if(dumpclonedclasses && Fieldobjectclone! =fieldobject) {System.out.println ("Cloned field>" + field + "--of class" +O.getclass ()); } }}}

Recursively go down and find a reference to the referenced reference of field reference .... Then they were all newinstance.

Java-deep Clone

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.