Life with teacher Lemon.

合并 Java Bean

2021.03.30 | 共 358 字,阅读需约 1 分钟.

在开发过程中有时需要在业务逻辑处理 Java Bean 时需要对部分属性做更新,每个属性都做 set 操作过于繁琐,可以利用反射来进行两个 Java Bean 的合并操作。

package com.sanoon;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.security.AccessController;
import java.security.PrivilegedAction;

/**
 * 合并两个Java Bean的属性
 *
 * @author sanoon
 */
public final class CombineUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(CombineUtil.class);

    private static final String SERIAL_VERSION_UID = "serialVersionUID";

    private CombineUtil() {
    }

    /**
     * sourceBean中的属性会覆盖目标bean
     * sourceBean属性有值,则替换目标bean的属性,返回被覆盖后的目标bean
     * sourceBean属性没有值,则保留目标bean的属性,返回被覆盖后的目标bean
     *
     * @param <T> Bean
     * @param sourceBean 新的bean
     * @param targetBean 被覆盖的目标bean
     */
    public static <T> void combine(T sourceBean, T targetBean) throws IllegalAccessException {
        Class<?> sourceBeanClass = sourceBean.getClass();
        Class<?> targetBeanClass = targetBean.getClass();

        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
        Field[] targetFields = targetBeanClass.getDeclaredFields();
        for (int i = 0; i < sourceFields.length; i++) {
            Field sourceField = sourceFields[i];
            if (Modifier.isStatic(sourceField.getModifiers())) {
                continue;
            }
            Field targetField = targetFields[i];
            if (Modifier.isStatic(targetField.getModifiers())) {
                continue;
            }
            AccessController.doPrivileged((PrivilegedAction<T>) () -> {
                sourceField.setAccessible(true);
                targetField.setAccessible(true);
                return null;
            });
            try {
                if (sourceField.get(sourceBean) != null 
                    && !SERIAL_VERSION_UID.equals(sourceField.getName())) {
                    targetField.set(targetBean, sourceField.get(sourceBean));
                }
            } catch (IllegalArgumentException | IllegalAccessException e) {
                LOGGER.error("Merge bean failed, the reason is {}.", e.getMessage());
                throw e;
            }
        }
    }
}
今日诗词