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 {
If the serialization interface is implemented, even if the class is implemented, the object he has is not necessarily ...
if (Serializable.class.isAssignableFrom (Obj.getclass ())) {
If the subclass does not inherit the interface, this step will cause an error
try {
return copyimplserializable (obj);
catch (Exception e) {
Not processed here, will run to the following try Json
}
}
If serialization fails, try JSON serialization way
if (Hasjson ()) {
try {
return Copybyjson (obj);
catch (Exception e) {
This is not handled here, NULL is returned below
}
}
return null;
}
/**
* Deep copy-require class to inherit the 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 cause 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's no need to handle the error.
}
}
}
/**
* Whether you can use JSON
* @return
*/
private static Boolean Hasjson () {
try {
Class.forName ("Net.sf.json.JSONObject");
return true;
catch (Exception e) {
return false;
}
}
/**
* Deep copy-Need 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.