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 ();}}