天天看點

BeanUtils 是用 Spring 的還是 Apache ,那個效率更好。

說明:

在我們實際項目開發過程中,我們經常需要将不同的兩個對象執行個體進行屬性複制,進而基于源對象的屬性資訊進行後續操作,而不改變源對象的屬性資訊,比如DTO資料傳輸對象和資料對象DO,我們需要将DO對象進行屬性複制到DTO,但是對象格式又不一樣,是以我們需要編寫映射代碼将對象中的屬性值從一種類型轉換成另一種類型。

這種轉換最原始的方式就是手動編寫大量的 ​

​get/set​

​​代碼,當然這是我們開發過程不願意去做的,因為它确實顯得很繁瑣。為了解決這一痛點,就誕生了一些友善的類庫,常用的有 apache的 ​

​BeanUtils​

​​,spring的 ​

​BeanUtils​

​​, ​

​Dozer​

​​,​

​Orika​

​等拷貝工具。

Apache下的BeanUtils 的實作如下:

public void copyProperties(final Object dest, final Object orig)
        throws IllegalAccessException, InvocationTargetException {

        // Validate existence of the specified beans
        if (dest == null) {
            throw new IllegalArgumentException
                    ("No destination bean specified");
        }
        if (orig == null) {
            throw new IllegalArgumentException("No origin bean specified");
        }
        if (log.isDebugEnabled()) {
            log.debug("BeanUtils.copyProperties(" + dest + ", " +
                      orig + ")");
        }

        // Copy the properties, converting as necessary
        if (orig instanceof DynaBean) {
            final DynaProperty[] origDescriptors =
                ((DynaBean) orig).getDynaClass().getDynaProperties();
            for (DynaProperty origDescriptor : origDescriptors) {
                final String name = origDescriptor.getName();
                // Need to check isReadable() for WrapDynaBean
                // (see Jira issue# BEANUTILS-61)
                if (getPropertyUtils().isReadable(orig, name) &&
                    getPropertyUtils().isWriteable(dest, name)) {
                    final Object value = ((DynaBean) orig).get(name);
                    copyProperty(dest, name, value);
                }
            }
        } else if (orig instanceof Map) {
            @SuppressWarnings("unchecked")
            final
            // Map properties are always of type <String, Object>
            Map<String, Object> propMap = (Map<String, Object>) orig;
            for (final Map.Entry<String, Object> entry : propMap.entrySet()) {
                final String name = entry.getKey();
                if (getPropertyUtils().isWriteable(dest, name)) {
                    copyProperty(dest, name, entry.getValue());
                }
            }
        } else /* if (orig is a standard JavaBean) */ {
            final PropertyDescriptor[] origDescriptors =
                getPropertyUtils().getPropertyDescriptors(orig);
            for (PropertyDescriptor origDescriptor : origDescriptors) {
                final String name = origDescriptor.getName();
                if ("class".equals(name)) {
                    continue; // No point in trying to set an object's class
                }
                if (getPropertyUtils().isReadable(orig, name) &&
                    getPropertyUtils().isWriteable(dest, name)) {
                    try {
                        final Object value =
                            getPropertyUtils().getSimpleProperty(orig, name);
                        copyProperty(dest, name, value);
                    } catch (final NoSuchMethodException e) {
                        // Should not happen
                    }
                }
            }
        }

    }      

Apache下的BeanUtils 的 對于對象拷貝加了很多的檢驗,包括類型的轉換,甚至還會檢驗對象所屬的類的可通路性,可謂相當複雜,這也造就了它的差勁的性能。

由于 Apache下的BeanUtils對象拷貝性能太差,不建議使用,而且在阿裡巴巴Java開發規約插件上也明确指出。

spring的 BeanUtils

private static void copyProperties(Object source, Object target, @Nullable Class<?> editable,
   @Nullable String... ignoreProperties) throws BeansException {

  Assert.notNull(source, "Source must not be null");
  Assert.notNull(target, "Target must not be null");

  Class<?> actualEditable = target.getClass();
  if (editable != null) {
   if (!editable.isInstance(target)) {
    throw new IllegalArgumentException("Target class [" + target.getClass().getName() +
      "] not assignable to Editable class [" + editable.getName() + "]");
   }
   actualEditable = editable;
  }
  PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
  List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);

  for (PropertyDescriptor targetPd : targetPds) {
   Method writeMethod = targetPd.getWriteMethod();
   if (writeMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
    PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
    if (sourcePd != null) {
     Method readMethod = sourcePd.getReadMethod();
     if (readMethod != null &&
       ClassUtils.isAssignable(writeMethod.getParameterTypes()[0], readMethod.getReturnType())) {
      try {
       if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
        readMethod.setAccessible(true);
       }
       Object value = readMethod.invoke(source);
       if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
        writeMethod.setAccessible(true);
       }
       writeMethod.invoke(target, value);
      }
      catch (Throwable ex) {
       throw new FatalBeanException(
         "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
      }
     }
    }
   }
  }
 }      

總結: