1 importlombok.extern.slf4j.Slf4j;2 importorg.springframework.beans.BeanUtils;3 importorg.springframework.beans.BeansException;4 importorg.springframework.beans.FatalBeanException;5 importorg.springframework.util.Assert;6 importorg.springframework.util.ClassUtils;717
18 /**
19 *@authorLiJing20 * @ClassName: BeanUtils21 * @Description: 属性拷贝工具类22 * @date 2018/4/10 11:5423 */
24 @Slf4j25 public class MyBeanUtils extendsBeanUtils {26
27 /**
28 * 从org.springframework.beans.BeanUtils类中直接复制过来29 *30 *@paramsource31 *@paramtarget32 *@throwsBeansException33 */
34 public static void copyProperties(Object source, Object target) throwsBeansException {35 copyProperties(source, target, null, (String[]) null);36 }37
38 /**
39 * 从org.springframework.beans.BeanUtils类中直接复制过来,修改部分代码,不为null才复制40 *41 *@paramsource42 *@paramtarget43 *@parameditable44 *@paramignoreProperties45 *@throwsBeansException46 */
47 private static void copyProperties(Object source, Object target, Class>editable, String... ignoreProperties)48 throwsBeansException {49
50 Assert.notNull(source, "Source must not be null");51 Assert.notNull(target, "Target must not be null");52
53 Class> actualEditable =target.getClass();54 if (editable != null) {55 if (!editable.isInstance(target)) {56 throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
57 "] not assignable to Editable class [" + editable.getName() + "]");58 }59 actualEditable =editable;60 }61 PropertyDescriptor[] targetPds =getPropertyDescriptors(actualEditable);62 List ignoreList = (ignoreProperties != null) ? Arrays.asList(ignoreProperties) : null;63
64 for(PropertyDescriptor targetPd : targetPds) {65 Method writeMethod =targetPd.getWriteMethod();66 if (writeMethod != null && (ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {67 PropertyDescriptor sourcePd =getPropertyDescriptor(source.getClass(), targetPd.getName());68 if (sourcePd != null) {69 Method readMethod =sourcePd.getReadMethod();70 if (readMethod != null && ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {71 try{72 if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {73 readMethod.setAccessible(true);74 }75 Object value =readMethod.invoke(source);76 //判断被复制的属性是否为null, 如果不为null才复制
77 if (value != null) {78 if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {79 writeMethod.setAccessible(true);80 }81 writeMethod.invoke(target, value);82 }83 } catch(Throwable ex) {84 throw newFatalBeanException(85 "不能拷贝属性 '" + targetPd.getName() + "' 从原对象给目标对象,详细原因见:", ex);86 }87 }88 }89 }90 }91 }92
93
94 /**
95 * 构造函数.96 */
97 publicMyBeanUtils() {98 throw new RuntimeException("this is a util class,can not instance");99 }
411 }