In the development process, you may encounter a new object that we need to have the same data as an object, but not the same memory address, this time we need to use Clone ().
But. Note that Clone () is divided into shallow and deep copies. The difference is whether the object being copied has non-basic variables.
1. If an object is this:
1 Public classCloneman {2 /** 3 * @fields ID clone ID4 */ 5 Private intID;6 /** 7 * @fields IsM clone sex8 */ 9 Private BooleanIsM;Ten One PublicCloneman (intIdBooleanIsM) { A This. ID =ID; - This. IsM =IsM; - } the - Public intgetId () { - returnID; - } + Public voidSetId (intID) { - This. ID =ID; + } A Public BooleanIsM () { at returnIsM; - } - Public voidSetm (BooleanIsM) { - This. IsM =IsM; - } -}
Cloneman class has only the member variables of the basic variable type, then clone one, only need to implement the Cloneable interface, overriding the Clone () method can be
1 Public classClonemanImplementscloneable{2 /** 3 * @fields ID clone ID4 */ 5 Private intID;6 /** 7 * @fields IsM clone sex8 */ 9 Private BooleanIsM;Ten One PublicCloneman (intIdBooleanIsM) { A This. ID =ID; - This. IsM =IsM; - } the - Public intgetId () { - returnID; - } + Public voidSetId (intID) { - This. ID =ID; + } A Public BooleanIsM () { at returnIsM; - } - Public voidSetm (BooleanIsM) { - This. IsM =IsM; - } - in PublicCloneman Clone () { - Try { to return(Cloneman)Super. Clone (); +}Catch(clonenotsupportedexception e) { - e.printstacktrace (); the return NULL; * } $ }Panax Notoginseng}
A new Cloneman object can be obtained through the Clone () method.
However, if a member variable of a class that needs to be cloned includes a non-primitive type, such as a string, then this method is invalidated. Because the non-basic variable type in it also needs to override the Clone () method, which I think is too much trouble.
By looking up the data, I know a way to clone objects via IO stream, and the pro-test is effective
Public Staticobject Deepclone (Object obj) {//to write an object to the streamBytearrayoutputstream bo =NewBytearrayoutputstream (); Try{ObjectOutputStream oo=NewObjectOutputStream (bo); Oo.writeobject (obj); //read the object from the streamBytearrayinputstream bi =NewBytearrayinputstream (Bo.tobytearray ()); ObjectInputStream Oi=NewObjectInputStream (BI); returnOi.readobject (); } Catch(IOException e) {e.printstacktrace (); return NULL; } Catch(ClassNotFoundException e) {e.printstacktrace (); return NULL; } }
# # #注意: The object passed here is to implement the Serializable interface serializable###
What we get here is an object that can be obtained after fetching to the desired type, and what I'm dealing with is that if there is an exception returned is null, so get a non-null judgment after getting it.
Because this is a common method, you can uninstall the public in the Ioutil
Cloning (clone) an object in Java