-
对象拷贝
-
List 对象拷贝
-
Map 拷贝
-
json 转 Map
-
获取对象 空属性
-
bean数组 转 bean数组
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.util.CollectionUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
/**
* @program: xxx
* @description: Bean 转换工具类
* @author: 52Hz
* @create: 2021-10-21 16:31
**/
public class BeanUtil {
/**
* 对象拷贝
*
* @param source 源
* @param target 目标
*/
public static void copyProperties(Object source, Object target) {
if (source == null) {
return;
}
BeanUtils.copyProperties(source, target);
}
/**
* List 对象拷贝
*
* @param list 源
* @param <T> 目标
* @return 目标
*/
public static <T, E> List copyList(List<T> list, Class<E> clazz) {
if (CollectionUtils.isEmpty(list)) {
return new ArrayList();
}
return JSON.parseArray(JSON.toJSONString(list), clazz);
}
/**
* MAP拷贝
*
* @param map 源
* @return 目标
*/
public static Map<String, Object> copyMap(Map map) {
if (CollectionUtils.isEmpty(map)) {
return new HashMap<>();
}
return JSON.parseObject(JSON.toJSONString(map));
}
/**
* json 转 Map
*
* @param json
* @return
*/
public static Map<String, Object> jsonToMap(String json) {
try {
ObjectMapper objectMapper = new ObjectMapper();
return objectMapper.readValue(json, Map.class);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
/**
* 获取对象 空属性
*
* @param source
* @return
*/
private static String[] getNullPropertyNames(Object source) {
BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = (Set) Arrays.stream(pds).filter((pd) -> {
return src.getPropertyValue(pd.getName()) == null;
}).map(FeatureDescriptor::getName).distinct().collect(Collectors.toSet());
String[] result = new String[emptyNames.size()];
return (String[])emptyNames.toArray(result);
}
/**
* bean数组 转 bean数组
*
* @param source
* @param function
* @param <T>
* @param <R>
* @return
*/
public static <T, R> List<R> covert2JavaBeanList(List<T> source, Function<T, R> function) {
if (null == source || source.size() < 0) {
return new ArrayList<>();
}
List<R> res = new ArrayList<>(source.size());
for (T t : source) {
res.add(function.apply(t));
}
return res;
}
}