package com;
import cn.hutool.core.convert.Convert;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.beans.PropertyDescriptor;
import java.util.*;
public class QQCopy {
//region 对象
@SneakyThrows
public static <T> T copy(Object source, Class<T> target) {
if (source == null || target == null)
return null;
T t = target.newInstance();
BeanUtils.copyProperties(source, t);
return t;
}
//复制对象属性,一个改变另一个也改变
@SneakyThrows
public static <T> T copyChange(Object source, Class<T> target) {
return Convert.convert(target, source);
}
//复制对象属性到另一个对象,修改不会改变
public static void copyProperties(Object source, Object target) {
BeanUtils.copyProperties(source, target);
}
//复制对象属性到另一个对象,只复制属性有值的,修改不会改变
public static void copyKeepValue(Object source, Object target) {
String[] names = getNullPropertyNames(source);
BeanUtils.copyProperties(source, target, names);
}
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<String>();
for (PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (srcValue == null) emptyNames.add(pd.getName());
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
// public static <T> List<T> copyList(List<?> sourceList, Class<T> target) {
// return sourceList.stream().map(s -> copy(s, target)).collect(Collectors.toList());
// }
//
// public static <T> Set<T> copySet(Set<?> sourceList, Class<T> target) {
// return sourceList.stream().map(s -> copy(s, target)).collect(Collectors.toSet());
// }
//endregion
}