工具类代码
代码语言:javascript复制import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
/**
* List类型转换工具类
*/
@Slf4j
public class BeanHelper {
public static <T> T copyProperties(Object source, Class<T> target){
try {
T t = target.newInstance();
BeanUtils.copyProperties(source, t);
return t;
} catch (Exception e) {
log.error("【数据转换出错】", target.getName(), e);
return null;
}
}
//List类型转换
public static <T> List<T> copyWithCollection(List<?> sourceList, Class<T> target){
try {
return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toList());
} catch (Exception e) {
log.error("【数据转换出错】", target.getName(), e);
return null;
}
}
//Set类型转换
public static <T> Set<T> copyWithCollection(Set<?> sourceList, Class<T> target){
try {
return sourceList.stream().map(s -> copyProperties(s, target)).collect(Collectors.toSet());
} catch (Exception e) {
log.error("【数据转换出错】", target.getName(), e);
return null;
}
}
}
导包
我用的是SpringBoot,缺哪个就导入那个
导入lombok
和beans
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<scope>compile</scope>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>