BeanUtils.copyProperties使用的時候,空值也被拷貝使它邊的很雞肋。spring
下面對他進行擴展,支持多種空值再也不拷貝spa
public abstract class BeanUtils extends org.springframework.beans.BeanUtils { public static void copyProperties(Object source, Object target) throws BeansException { Assert.notNull(source, "Source must not be null"); Assert.notNull(target, "Target must not be null"); 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) { boolean isEmpty = false; if (value instanceof Set) { Set s = (Set) value; if (s == null || s.isEmpty()) { isEmpty = true; } } else if (value instanceof Map) { Map m = (Map) value; if (m == null || m.isEmpty()) { isEmpty = true; } } else if (value instanceof List) { List l = (List) value; if (l == null || l.size() < 1) { isEmpty = true; } } else if (value instanceof Collection) { Collection c = (Collection) value; if (c == null || c.size() < 1) { isEmpty = true; } } if (!isEmpty) { Method writeMethod = targetPd.getWriteMethod(); if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) { writeMethod.setAccessible(true); } writeMethod.invoke(target, value); } } } catch (Throwable ex) { throw new FatalBeanException("Could not copy properties from source to target", ex); } } } } } }