复制对象的属性值,可以是相同类型对象,也可以是不同类型对象,主要是同名属性的赋值
警告:
- 尽量不要用于不同类型的属性复制
- 不同类型的对象,同名的属性,如果类型不同,很可能无法复制
- 属性的名字大小写必须完全相同才能复制
- import org.springframework.beans.BeanUtils;
- import org.springframework.beans.BeanWrapper;
- import org.springframework.beans.BeanWrapperImpl;
- import java.beans.PropertyDescriptor;
- import java.util.HashSet;
- import java.util.Objects;
- import java.util.Set;
- * Copy bean utility class
- */
- public class CopyBeanUtils {
- private CopyBeanUtils() {
- throw new IllegalStateException("Utility class");
- }
-
- * All attributes with null values are not copied
- *
- * @param source source object
- * @param target target object
- */
- public static void copyNonNullPropertites(Object source, Object target) {
- BeanUtils.copyProperties(source, target, getNullField(source));
- }
-
- * Get fields that are empty in the property
- *
- * @param source source object
- * @return array name of null fields
- */
- private static String[] getNullField(Object source) {
- BeanWrapper beanWrapper = new BeanWrapperImpl(source);
- PropertyDescriptor[] propertyDescriptors = beanWrapper.getPropertyDescriptors();
- Set<String> notNullFieldSet = new HashSet<>();
- for (PropertyDescriptor p : propertyDescriptors) {
- String name = p.getName();
- Object value = beanWrapper.getPropertyValue(name);
- if (Objects.isNull(value)) {
- notNullFieldSet.add(name);
- }
- }
- String[] notNullField = new String[notNullFieldSet.size()];
- return notNullFieldSet.toArray(notNullField);
- }
- }