当前位置: 代码迷 >> 综合 >> BeanUtils.copyProperties和普通赋值比较
  详细解决方案

BeanUtils.copyProperties和普通赋值比较

热度:60   发布时间:2023-12-11 20:54:06.0

其实不难理解,一看代码就知道spring用反射究竟多做了多少事情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) {
if (targetPd.getWriteMethod() != null &&(ignoreProperties == null || (!ignoreList.contains(targetPd.getName())))) {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);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);}}}}
}大致过程是,现根据object获得class,根据class获得PropertyDescriptor[],然后获得此property的WriteMethod,判断这个method是否是虚方法,是否是public,如果都ok了,就调用这个method赋值,【每一个method都会进行这轮判断】

  相关解决方案