BeanUtils.copyProperties()笔记

来源:互联网 发布:c语言的开发环境 编辑:程序博客网 时间:2024/06/05 09:51

最近在学习Spring-boot,视频教学里面有用到这个方法来复制对象的属性。


方法这么多,为什么单独拿这个出来记录呢,因为这个方法可以在不同类型的对象之间复制属性值,看了一下源码,还没有完全看明白,先记录一下。


先上源码:


/** * 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);}}}}}}



源码还有一部分没有看懂,先记录下暂时的理解:

1.源和目标没有类型的限定的情况下属性名称是否一定要相同?

--属性名称一定要相同,并且类型也要相同,否则无法复制属性.

2.目标对象已经有值的情况下,是否还会把源对象里面的属性值覆盖目标对象的属性值。

--会,即使源对象中某属性的值为Null,目标对象中某属性的值不为null,也会把null值赋值给非null值,所以使用的时候要特别注意,可以先复制,再做一些不需要复制的属性的赋值.

3.如果相同名称的属性值数据类型不一样是否会抛出异常,什么时候回抛出异常?

--如果数据类型能转换,会自动转换,如果不能转换就会报错

原创粉丝点击