37 lines
1.2 KiB
Java
37 lines
1.2 KiB
Java
package com.darkness.common.util;
|
|
|
|
import org.springframework.beans.BeanUtils;
|
|
import org.springframework.util.CollectionUtils;
|
|
|
|
import java.util.ArrayList;
|
|
import java.util.List;
|
|
import java.util.Objects;
|
|
|
|
public class ConvertUtils {
|
|
|
|
public static <S, T> List<T> convertList(List<S> sourceList, Class<T> clazz) {
|
|
if (CollectionUtils.isEmpty(sourceList)) {
|
|
return new ArrayList<>();
|
|
}
|
|
List<T> targetList = new ArrayList<>(sourceList.size());
|
|
for (S sourceObj : sourceList) {
|
|
if (Objects.nonNull(sourceObj)) {
|
|
T targetObj = BeanUtils.instantiateClass(clazz);
|
|
BeanUtils.copyProperties(sourceObj, targetObj);
|
|
targetList.add(targetObj);
|
|
} else {
|
|
targetList.add(null); // 或者根据业务需求决定是否添加null
|
|
}
|
|
}
|
|
return targetList;
|
|
}
|
|
public static <T, S> T convertObj(S sourceObj, Class<T> clazz) {
|
|
if (Objects.isNull(sourceObj)) {
|
|
return null;
|
|
}
|
|
T targetObj = BeanUtils.instantiateClass(clazz);
|
|
BeanUtils.copyProperties(sourceObj, targetObj);
|
|
return targetObj;
|
|
}
|
|
}
|