Beanutils.copyProperties( )
一、簡介:
BeanUtils
提供對Java反射和自省API的包裝。其主要目的是利用反射機制對JavaBean
的屬性進行處理。我們知道,一個JavaBean
通常包含了大量的屬性,很多情況下,對JavaBean
的處理導致大量get
/set
代碼堆積,增加了代碼長度和閱讀代碼的難度。
二、詳情:
如果你有兩個具有很多相同屬性的JavaBean
,需要對象之間的賦值,這時候就可以使用這個方法,避免代碼中全是get
/set
之類的代碼,可以讓代碼簡潔明朗更優雅。
源碼中的核心代碼:
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);
}
}
}
}
}
}
source
是源對象,target
是需要賦值的對象
所需的maven
依賴(spring-boot里面已經集成了spring-bean,所以不需要單獨導入):
<!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>5.2.0.RELEASE</version>
</dependency>
說明:
賦值成功的屬性對應的屬性名和屬性類型必須相同,否則對應的屬性值不會從一個對象賦值給另一個對象,但是此時不影響其他屬性值的拷貝。
三、使用
將符合條件的屬性值全部從一個對象賦值給另一個對象
copyProperties(Object source, Object target)
BeanUtils.copyProperties(model01,model02);
將對象model01
里面的值賦給model02
如果有些對象沒有屬性,則需要我們手動添加
如果有些對象不想賦值,需要我們手動設置
忽略某些屬性的賦值
copyProperties(Object source, Object target, String... ignoreProperties)
//定義name不賦值
String[] ignoreProperties = {"name"};
BeanUtils.copyProperties(model01,model02,ignoreProperties);
最后:1024節日快樂,加班讓我快樂...