BeanConverUtil.java
1.4 KB
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
package cn.com.glsx.entmicro.util;
import com.alibaba.nacos.client.naming.utils.CollectionUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
@Slf4j
public class BeanConverUtil {
/**
* 单个类转换
*
* @param sourceObj
* @param targetClass
* @param <T>
* @return
*/
public static <T> T conver(Object sourceObj, Class<T> targetClass) {
if (sourceObj == null || targetClass == null) {
return null;
}
T targetObj = null;
try {
targetObj = targetClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
log.error("sourceObj:{},targetClass:{}", sourceObj, targetClass, e);
return null;
}
BeanUtils.copyProperties(sourceObj, targetObj);
return targetObj;
}
/**
* List之间转换
*
* @param sourceList
* @param targetClass
* @param <T>
* @return
*/
public static <T> List<T> converList(List<?> sourceList, Class<T> targetClass) {
if (CollectionUtils.isEmpty(sourceList) || targetClass == null) {
return Collections.emptyList();
}
return sourceList.stream().map(sourceObj -> conver(sourceObj, targetClass)).collect(Collectors.toList());
}
}