Detailed description of using JAVA deep copy DeepCopy

Source: Internet
Author: User

Recently, we need to compare the changes of two object attributes, one of which is oldObj, the other is newObj, And the oldObj is the previous status of newObj. Therefore, when newObj is in a certain state, copy the same object. Because JAVA does not support deep copy, a method is specially written.

The method implementation is very simple. Two methods are provided:
One is to serialize data streams, provided that all objects are included in the object ...) all must inherit the Serializable interface. If all inherit, it is very easy. If there is no inheritance, and you do not intend to modify all classes, you can use the second method.

The second method is to serialize the object to json and copy it through json. net. sf. json. JSONObject is required in this method.
The Code is as follows:

Copy codeThe Code is 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 this class is implemented, its own objects may not exist...
If (Serializable. class. isAssignableFrom (obj. getClass ())){
// If the subclass does not inherit this interface, an error is returned in this step.
Try {
Return copyImplSerializable (obj );
} Catch (Exception e ){
// If this is not processed, it will run to the following try json
}
}
// If serialization fails, try the json serialization Method
If (hasJson ()){
Try {
Return copyByJson (obj );
} Catch (Exception e ){
// Not processed here, and null is returned below
}
}
Return null;
}

/**
* Deep copy-class inheritance serialization interface required
* @ 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 this interface, an error is returned in this step.
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 ("the object contains objects that do not inherit serialization ");
} Finally {
Try {
Baos. close ();
Oos. close ();
Bais. close ();
Ois. close ();
} Catch (Exception e2 ){
// You do not need to handle the error.
}
}
}

/**
* Whether json can be used
* @ Return
*/
Private static boolean hasJson (){
Try {
Class. forName ("net. sf. json. JSONObject ");
Return true;
} Catch (Exception e ){
Return false;
}
}

/**
* Deep copy-net. sf. json. JSONObject is required
* @ 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 call the copy method.

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.