perf:对hutool的BeanUtil工具类做补充

分享一个自定义的BeanUtil,继承的是hutool的工具类,然后自己扩充了几个方法;

1、实现了两个对象覆盖非空属性的功能(经常使用),不需要设置CopyOptions;

2、两个对象,对指定前缀的属性进行拷贝,其中copyExtendProperties就会拷贝对象中的extend1,extend2,extend3...等等。

@Slf4j
@UtilityClass
public class MyBeanUtils extends BeanUtil {

    /**
     * 两个对象覆盖非空属性(忽略指定字段)
     *
     * @param source        源 bean
     * @param target        目标 bean
     * @param ignoresFields 忽略的字段列表
     */
    public static <S, T> void overrideNonNullProperties(S source, T target, String... ignoresFields) {
        Map<String, Object> sourceMap = BeanUtil.beanToMap(source, false, false);
        Map<String, Object> targetMap = BeanUtil.beanToMap(target, false, false);
        overrideNonNullPropertiesInternal(sourceMap, target, targetMap, ignoresFields);
    }

    /**
     * 将 Map 赋值非空属性到指定对象(忽略指定字段)
     *
     * @param sourceMap     源 Map
     * @param target        目标 bean
     * @param ignoresFields 忽略的字段列表
     */
    public static <T> void overrideNonNullProperties(Map<String, Object> sourceMap, T target, String... ignoresFields) {
        Map<String, Object> targetMap = BeanUtil.beanToMap(target, false, false);
        overrideNonNullPropertiesInternal(sourceMap, target, targetMap, ignoresFields);
    }

    /**
     * 内部方法,处理覆盖非空属性的逻辑
     *
     * @param sourceMap     源对象的属性映射
     * @param target        目标对象
     * @param targetMap     目标对象的属性映射
     * @param ignoresFields 忽略的字段列表
     */
    private static <T> void overrideNonNullPropertiesInternal(Map<String, Object> sourceMap, T target,
                                                              Map<String, Object> targetMap, String... ignoresFields) {
        // 移除忽略的字段
        for (String field : ignoresFields) {
            targetMap.remove(field);
        }

        // 遍历源对象的属性,只处理非空值,并确认目标对象中存在该字段
        sourceMap.forEach((fieldName, value) -> {
            if (value != null && targetMap.containsKey(fieldName)) {
                BeanUtil.setFieldValue(target, fieldName, value);
            }
        });
    }

    /**
     * 将源对象的属性通过反射赋值到目标对象(只处理以 "extend" 开头的字段)
     *
     * @param source 源对象
     * @param target 目标对象
     */
    public static void copyExtendProperties(Object source, Object target) {
        copyPropertiesWithPrefix(source, target, "extend");
    }

    /**
     * 将源对象的属性通过反射赋值到目标对象(只处理以指定前缀开头的字段)
     *
     * @param source             源对象
     * @param target             目标对象
     * @param propertyNamePrefix 处理的字段名前缀
     * @param ignoresFields      忽略的字段列表
     */
    public static void copyPropertiesWithPrefix(Object source, Object target, String propertyNamePrefix, String... ignoresFields) {
        Field[] fields = source.getClass().getDeclaredFields();
        Set<String> ignoresSet = Set.of(ignoresFields);

        for (Field field : fields) {
            String fieldName = field.getName();

            if (fieldName.startsWith(propertyNamePrefix)) {
                try {
                    ReflectionUtils.makeAccessible(field);
                    Object value = field.get(source);

                    if (value != null) {
                        Field targetField = getTargetField(fieldName, target.getClass());

                        if (targetField != null && !ignoresSet.contains(fieldName)) {
                            ReflectionUtils.makeAccessible(targetField);
                            ReflectionUtils.setField(targetField, target, value);
                        }
                    }
                } catch (IllegalAccessException e) {
                    log.error("非法访问字段: {}", fieldName, e);
                }
            }
        }
    }

    /**
     * 安全地获取目标对象中的字段。
     *
     * @param fieldName 字段名
     * @param clazz     目标对象的类对象
     * @return 目标字段或null(如果未找到)
     */
    private static Field getTargetField(String fieldName, Class<?> clazz) {
        try {
            Field field = ReflectionUtils.findField(clazz, fieldName);
            if (field == null) {
                log.debug("目标对象中未找到字段: {}", fieldName);
            }
            return field;
        } catch (Exception e) {
            log.error("获取目标字段异常: {}", fieldName, e);
            return null;
        }
    }
}

ps:以下是我整理的java面试资料,感兴趣的可以看看。最后,创作不易,觉得写得不错的可以点点关注!

链接:https://www.yuque.com/u39298356/uu4hxh?# 《Java知识宝典》 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值