BeanUtils.copyProperties(Object source, Object target) method in spring

Package name of BeanUtils: org.springframework.beans

BeanUtils.copyProperties(a,b); // Copy the properties in a to b

The principle is to rely on set for attribute injection through java's reflection mechanism.

See the source code for details. But I'm lazy, I did a black box test first, and then looked at the source code roughly.

The source code is injected through the set, and the value is obtained from the source data a based on the target b attribute.

If the property does not exist in a, the property in b does nothing, that is, the value is null.

The following is part of the source code, about line 301 (after all, the version is different, the number of lines may be different)

Class<?> actualEditable = target.getClass();
// omit part of the code
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
List<String> ignoreList = ignoreProperties != null ? Arrays.asList(ignoreProperties) : null;
PropertyDescriptor[] var7 = targetPds;
int var8 = targetPds.length;

for(int var9 = 0; var9 < var8; ++var9) {
    PropertyDescriptor targetPd = var7[var9];
    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 var15) {
                    throw new FatalBeanException("Could not copy property '" + targetPd.getName() + "' from source to target", var15);
                }
            }
        }
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325812168&siteId=291194637