JAVA deep Copy deepcopy of the use of detailed

Source: Internet
Author: User
Tags inheritance json requires serialization
Recently, you need to compare two object properties, one of which is oldobj, and the other is that Newobj,oldobj is the previous state of newobj, so you need to copy one of the same objects in a state of newobj, because Java does not support deep copy, So specifically wrote a method

The implementation of the method is simple and offers two ways:
One is to serialize to a stream of data, provided that all objects (objects contained in the object ...) are serialized. You need to inherit the serializable interface, and if you inherit it, it's easy, if you don't inherit it, and you don't want to modify all the classes, you can use the second way.

The second is to serialize the object into JSON, using JSON to implement the copy, which requires the use of net.sf.json.JSONObject.
The specific code is as follows:

Copy Code code as follows:


public class Deepcopy {


        /**


* Deep Copy


         * 


* @param <T>


* @param obj


* @return


* @throws Exception


         */ 


public static <T> t copy (T obj) throws Exception {


//Whether the serialization interface is implemented, even if the class is implemented, the object he owns may not have ...


if (Serializable.class.isAssignableFrom (Obj.getclass ()) {


//If the subclass does not inherit the interface, this step will be an error


try {


return copyimplserializable (obj);


catch (Exception e) {


//Here does not handle, will run to the following try JSON


                } 


            } 


//If serialization fails, try JSON serialization method


if (Hasjson ()) {


try {


return Copybyjson (obj);


catch (Exception e) {


//Here is not handled, the following returns null


                } 


            } 


return null;


        } 





        /**


* Deep copy-requires class inheritance serialization interface


* @param <T>


* @param obj


* @return


* @throws Exception


         */ 


@SuppressWarnings ("unchecked")


public static <T> t copyimplserializable (t obj) throws Exception {


Bytearrayoutputstream BAOs = null;


ObjectOutputStream oos = null;





Bytearrayinputstream Bais = null;


ObjectInputStream ois = null;





Object o = null;


//If the subclass does not inherit the interface, this step will be an error


try {


BAOs = new Bytearrayoutputstream ();


Oos = new ObjectOutputStream (BAOs);


oos.writeobject (obj);


Bais = new Bytearrayinputstream (Baos.tobytearray ());


OIS = new ObjectInputStream (Bais);





o = Ois.readobject ();


return (T) O;


} catch (Exception e) {


throw new Exception ("object contains objects with no inheritance serialization");


} finally{


try {


Baos.close ();


Oos.close ();


Bais.close ();


Ois.close ();


} catch (Exception E2) {


//There is no need to deal with the error


                }


            } 


        } 





        /**


* Can I use JSON


* @return


         */ 


private Static Boolean Hasjson () {


try {


class.forname ("Net.sf.json.JSONObject");


return true;


catch (Exception e) {


return false;


            } 


        } 





        /**


* Deep copy-requires Net.sf.json.JSONObject


* @param <T>


* @param obj


* @return


* @throws Exception


         */ 


@SuppressWarnings ("unchecked")


public static <T> t Copybyjson (t obj) throws Exception {


return (T) Jsonobject.tobean (Jsonobject.fromobject (obj), Obj.getclass ());


        } 


    } 


You only need to invoke the Copy method on the line.

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.