Java depth Copy an object __java

Source: Internet
Author: User

A deep copy of a Java object, regardless of the parameters in the object, such as String, array, object type, or object type with an object type parameter.

And this copied object does not need to implement the serializable interface.


Import Java.io.ByteArrayInputStream;
Import Java.io.ByteArrayOutputStream;
Import java.io.IOException;
Import Java.io.ObjectInputStream;
Import Java.io.ObjectOutputStream;

/** *
 cloning operation class
 * @author Liguohui
 * * */public
class Cloneoper {
	/**
	 * deep copy
	 * @param obj
	 * @return
	 *
	/@SuppressWarnings ("unchecked") public
	static <T> t Deepcloneobject (t obj) {
		try {
			Bytearrayoutputstream byteout = new Bytearrayoutputstream ();
			ObjectOutputStream out = new ObjectOutputStream (byteout);
			Out.writeobject (obj);
			
			Bytearrayinputstream Bytein = new Bytearrayinputstream (Byteout.tobytearray ()); 
	        ObjectInputStream in =new ObjectInputStream (Bytein);
			
	        Return (T) in.readobject ();
		} catch (IOException e) {
			e.printstacktrace ();
		} catch (ClassNotFoundException e) {
			e.printstacktrace ();
		}
		return null;
	}
}


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.