三種複製屬性的工具java
1.cglibspring
import net.sf.cglib.beans.BeanCopier; BeanCopier copier = BeanCopier.create(User.class, User.class, false); copier.copy(source, user, null);
2.org.apache.commonsapache
import org.apache.commons.beanutils.BeanUtils; BeanUtils.copyProperties(user, source);
3.spring beansapp
org.springframework.beans.BeanUtils.copyProperties(source, user);
效率方面:工具
spring beans>=cglib>org.apache.commons.beanutils.BeanUtilsrest
org.springframework.beans.BeanUtils與net.sf.cglib.beans.BeanCopiercode
在同一個數量級,區別不大,比org.apache.commons.beanutils.BeanUtils效率快一個數量級.遞歸
org.springframework.beans.BeanUtils.copyProperties最終調用的是如下這個方法.ip
/** * Copy the property values of the given source bean into the given target bean. * <p>Note: The source and target classes do not have to match or even be derived * from each other, as long as the properties match. Any bean properties that the * source bean exposes but the target bean does not will silently be ignored. * @param source the source bean * @param target the target bean * @param editable the class (or interface) to restrict property setting to * @param ignoreProperties array of property names to ignore * @throws BeansException if the copying failed * @see BeanWrapper */ private static void copyProperties(Object source, Object target, Class<?> editable, 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); } } } } } }
以前覺得bean中有bean或List的會遞歸調用,實際上並無.用反射調用read method和write method.get