优雅的Pojo转换类封装,基于BeanUtils的链式封装(Transformer类)

前言

现实开发中经常遇到Pojo间的转换,手动写Conversion方法过于繁琐,而且代码中也会有很多冗余代码。为了偷懒干脆直接使用BeanUtils.copyProperties方法,可是每次结合lambda和链式时,总觉得直接使用BeanUtils中断链式不太舒服,因此封装了Transformer类。

Transformer类

/**
 * POJO转换便捷类
 *
 * @author wanggf
 */
public final class Transformer<SOURCE, TARGET> {
    private final Supplier<TARGET> supplier;
    private BiConsumer<SOURCE, TARGET> consumer;

    /**
     * 构造器
     *
     * @param supplier 目标对象工厂
     */
    public Transformer(Supplier<TARGET> supplier) {
        this.supplier = supplier;
    }

    /**
     * 自定义填充方法
     * <p>链式使用该填充方法时需注意,如果编译器无法推断出{@link SOURCE}的类型,则可以显式指示该类型。</p>
     * <pre>new Transformer&lt;User, UserVo&get;(UserVo::new).fill((s, t) -> t.setUserId(s.getUserId))</pre>
     *
     * @param consumer 填充方法
     * @return 便捷类实例
     */
    public Transformer<SOURCE, TARGET> fill(BiConsumer<SOURCE, TARGET> consumer) {
        this.consumer = this.consumer == null ? consumer : this.consumer.andThen(consumer);
        return this;
    }

    /**
     * 自定义填充方法
     *
     * @param consumer 填充方法
     * @return 便捷类实例
     */
    public Transformer<SOURCE, TARGET> fill(Consumer<TARGET> consumer) {
        return fill((s, t) -> consumer.accept(t));
    }

    /**
     * 目标转换
     *
     * @param map 转换方法
     * @param <T> 目标类型
     * @return 新构造的便捷类实例
     */
    public <T> Transformer<TARGET, T> map(Function<TARGET, T> map) {
        return new Transformer<>(() -> map.apply(supplier.get()));
    }

    /**
     * 执行转换
     *
     * @param source 源对象
     * @return 目标对象
     */
    public TARGET transform(SOURCE source) {
        TARGET target = supplier.get();
        if (target != null && source != null) {
            BeanUtils.copyProperties(source, target);
            if (consumer != null) {
                consumer.accept(source, target);
            }
        }
        return target;
    }

    /**
     * 执行转换,并返回{@link Optional}对象
     *
     * @param source 源对象
     * @return {@link Optional}
     */
    public Optional<TARGET> transformDoOpt(SOURCE source) {
        return Optional.ofNullable(transformTo(source));
    }
}

示例

Transformer单对象转换

public CategoryVo getById(Long id) {
     Category category = iCategoryService.getById(id);
     if (category == null) {
         throw new RequestException(MostReturnStatus.NONEXISTENT_RESOURCE, "文章分类不存在");
     }
     return new Transformer<>(CategoryVo::new).fill(t -> {
         if (!Objects.equals(t.getParentId(), DataDefaultValueConst.DEFAULT_PARENT_ID)) {
             t.setParentName(getCategoryNameById(t.getParentId()));
         }
     }).transform(category);
 }

Transformer集合转换

public PageVo<PersonCategoryVo> listByTerm(CategoryParam categoryParam, PageParam pageParam, Subject subject) {
    PageVo<Category> categories = iCategoryService
        .listByName(categoryParam.getName(), subject.getUid(), pageParam.getDecrPage(), pageParam.getSize());
    return categories.map(new Transformer<>(PersonCategoryVo::new).fill(t -> {
        if (!Objects.equals(t.getParentId(), DataDefaultValueConst.DEFAULT_PARENT_ID)) {
            t.setParentName(getCategoryNameById(t.getParentId()));
        }
    })::transform);
}

仓库地址: https://github.com/cnwanggf/donkey-blog

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值