java反射复制属性值
1 /** 将sourceObj的属性拷贝到targetObj 2 * @param sourceObj 3 * @param targetObj 4 * @param clazz 从哪一个类开始(比如sourceObj对象层级为:Object->User->ChineseUser->ChineseMan->ChineseChongQingMan) 5 * 如果需要从ChineseUser开始复制,clazz就指定为ChineseUser.class 6 */ 7 public static void cpoyObjAttr(Object sourceObj, Object targetObj, Class<?> clazz)throws Exception 8 { 9 if(sourceObj==null || targetObj==null) 10 { 11 throw new Exception("源对象和目标对象不能为null"); 12 } 13 Field[] fields=clazz.getDeclaredFields(); 14 for(int i = 0; i < fields.length; i++) 15 { 16 //System.out.println(fields[i].getName()); 17 //Object sourceValue=fields[i].get(sourceObj); 18 19 Method getMethod = sourceObj.getClass().getMethod("get" + fields[i].getName()); 20 Object sourceValue = (Object) getMethod.invoke(sourceObj, null); 21 if(null==sourceValue) 22 { 23 sourceValue = null; 24 } 25 fields[i].setAccessible(true); 26 fields[i].set(targetObj,sourceValue); 27 28 // System.out.println(fields[i].getName()+";"+clazz+";"+fields[i].getType()); 29 // Method setMethod = targetObj.getClass().getMethod("set" +fields[i].getName(), fields[i].getType()); 30 // setMethod.invoke(targetObj, sourceValue.toString()); 31 } 32 if(clazz.getSuperclass()==Object.class){ 33 return; 34 } 35 cpoyObjAttr(sourceObj,targetObj,clazz.getSuperclass()); 36 }