/** * 拷贝属性到目标对象,如果为空不拷贝,目标对象属性有值,则不拷贝该属性 * * @param source * 待拷贝属性的对象 * @param target * 目标对象 * @throws BeansException */ public static void copyPropertiesExclude(Object source, Object target) throws BeansException { if (source == null || target == null) { throw new RuntimeException("拷贝和被拷贝对象不能为空。"); } Class<?> actualEditable = target.getClass(); PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable); for (PropertyDescriptor targetPd : targetPds) { if (targetPd.getWriteMethod() != null) { PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName()); if (sourcePd != null && sourcePd.getReadMethod() != null) { try { Method readMethod = sourcePd.getReadMethod(); if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) { readMethod.setAccessible(true); } Object value = readMethod.invoke(source); // 这里判断以下value是否为空 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等 if (value != null) { Method targetReadMethod = targetPd.getReadMethod(); if (!Modifier.isPublic(targetReadMethod.getDeclaringClass().getModifiers())) { targetReadMethod.setAccessible(true); } Object targetValue = targetReadMethod.invoke(target); Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } if(targetValue!=null && !StringUtils.isEmpty(targetValue.toString()) && !"[]".equals(targetValue.toString())){ continue; } writeMethod.invoke(target, value); } } catch (Throwable ex) { throw new FatalBeanException("Could not copy properties from source to target", ex); } } } } }
时间: 2024-11-08 01:24:22