1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
| /**
* 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<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));
}
}
|