潘志宝
9 天以前 6b13839488edcd06046e26a41fe897358176689c
提交 | 用户 | 时间
e7c126 1 package com.iailab.framework.common.util.object;
H 2
3 import cn.hutool.core.bean.BeanUtil;
4 import com.iailab.framework.common.pojo.PageResult;
5 import com.iailab.framework.common.util.collection.CollectionUtils;
6
7 import java.util.List;
8 import java.util.function.Consumer;
9
10 /**
11  * Bean 工具类
12  *
13  * 1. 默认使用 {@link cn.hutool.core.bean.BeanUtil} 作为实现类,虽然不同 bean 工具的性能有差别,但是对绝大多数同学的项目,不用在意这点性能
14  * 2. 针对复杂的对象转换,可以搜参考 AuthConvert 实现,通过 mapstruct + default 配合实现
15  *
16  * @author iailab
17  */
18 public class BeanUtils {
19
20     public static <T> T toBean(Object source, Class<T> targetClass) {
21         return BeanUtil.toBean(source, targetClass);
22     }
23
24     public static <T> T toBean(Object source, Class<T> targetClass, Consumer<T> peek) {
25         T target = toBean(source, targetClass);
26         if (target != null) {
27             peek.accept(target);
28         }
29         return target;
30     }
31
32     public static <S, T> List<T> toBean(List<S> source, Class<T> targetType) {
33         if (source == null) {
34             return null;
35         }
36         return CollectionUtils.convertList(source, s -> toBean(s, targetType));
37     }
38
39     public static <S, T> List<T> toBean(List<S> source, Class<T> targetType, Consumer<T> peek) {
40         List<T> list = toBean(source, targetType);
41         if (list != null) {
42             list.forEach(peek);
43         }
44         return list;
45     }
46
47     public static <S, T> PageResult<T> toBean(PageResult<S> source, Class<T> targetType) {
48         return toBean(source, targetType, null);
49     }
50
51     public static <S, T> PageResult<T> toBean(PageResult<S> source, Class<T> targetType, Consumer<T> peek) {
52         if (source == null) {
53             return null;
54         }
55         List<T> list = toBean(source.getList(), targetType);
56         if (peek != null) {
57             list.forEach(peek);
58         }
59         return new PageResult<>(list, source.getTotal());
60     }
61
bb2880 62     public static void copyProperties(Object source, Object target) {
H 63         if (source == null || target == null) {
64             return;
65         }
66         BeanUtil.copyProperties(source, target, false);
67     }
68
e7c126 69 }