JAVA clones objects, including parent class attributes, without the need to implement serialization Interfaces

Source: Internet
Author: User

Recently, an object needs to be copied, and the attributes of the parent class also need to be copied .. Many may say that you can directly reference the object to be copied. However, this method supports the use of subclass references to reference similar to the parent class. The following code is/** Java code: /** copy the sourceObj attribute to targetObj * @ param sourceObj * @ param targetObj * @ param clazz from which class (for example, the sourceObj object level is: object-> User-> ChineseUser-> ChineseMan-> ChineseChongQingMan) * if you need to copy data from ChineseUser, clazz is specified as ChineseUser. class */public static void cpoyObjAttr (Object sourceObj, Object targetObj, Class <?> Clazz) throws Exception {if (sourceObj = null | targetObj = null) {throw new Exception ("the source object and target object cannot be null ");} field [] fields = clazz. getDeclaredFields (); for (int I = 0; I <fields. length; I ++) {fields [I]. setAccessible (true); Object sourceValue = fields [I]. get (sourceObj); fields [I]. set (targetObj, sourceValue);} if (clazz. getSuperclass () = Object. class) {return;} cpoyObjAttr (sourceObj, targetObj, clazz. getSuperclass ();} The following is a unit Test: Java code: @ Test public void cpoyObjAttrTtest () {ChineseMan chineseMan = new ChineseMan (); chineseMan. setUserName ("programmer"); chineseMan. setCat (new Cat ("tom"); try {ChineseManExtend chineseManExtend = new ChineseManExtend (); ObjectTool. cpoyObjAttr (chineseMan, chineseManExtend, chineseMan. getClass (); System. out. println (chineseManExtend. getUserName (); System. out. println (chineseManExtend. getCat (). getCatName ();} catch (Exception e) {// TODO Auto-generated catch block e. printStackTrace ();}}

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.