程序实现的功能:将实体bean2的属性值拷贝至bean1,前提是bean2的属性存在于bean1 主方法 public static Object copyObject(Object obj1,Object obj2) throws Exception{ //得到object1类型全部属性 Class classType1 = obj1.getClass(); Field fields1[] = classType1.getDeclaredFields(); //得到object1类型全部属性 Class classType2 = obj2.getClass(); Field fields2[] = classType2.getDeclaredFields(); //复制 for (int i = 0 ; i<fields2.length ;i++){ String fieldName2 = fields2[i].getName(); //判断obj1中有无obj2属性 if(hasField(fields1, fieldName2)){ //set Or get 方法 Method getMethod= getMethodByGet(classType2, fieldName2); Method setMethod= getMethodBySet(classType1, fieldName2, fields2[i]); //拷贝obj2 to obj1,去空值 try{ Object value = getMethod.invoke(obj2, new Object[]{}); if(value != null) setMethod.invoke(obj1, new Object[]{value}); }catch(Exception E){ continue; } } } return obj1; } get,set方法 /** * 得到get方法 * @param classType2 * @param fieldName2 * @throws NoSuchMethodException */ private static Method getMethodByGet(Class classType, String fieldName) throws NoSuchMethodException { //第一个字母大写 String firestLetter = fieldName.substring(0,1).toUpperCase(); //得到getXXX方法名 String methodName = "get" + firestLetter + fieldName.substring(1); //得到对应的方法 Method method = classType.getMethod(methodName,new Class[]{}); return method; } /** * 得到set方法 * @param classType * @param fieldName * @return * @throws NoSuchMethodException */ private static Method getMethodBySet(Class classType, String fieldName, Field type) throws NoSuchMethodException { //第一个字母大写 String firestLetter = fieldName.substring(0,1).toUpperCase(); //得到getXXX方法名 String methodName = "set" + firestLetter + fieldName.substring(1); //得到对应的方法 Method method = classType.getMethod(methodName,new Class[]{type.getType()}); return method; } 判断属性是否存在 /** * 判断有无属性 * @param fields1 * @param fieldName2 */ private static boolean hasField(Field[] fields, String fieldName) { for (int j = 0 ; j < fields.length ; j++){ if(fieldName.equalsIgnoreCase(fields[j].getName())){ return true; } } return false; }