在springboot项目单靠实体类不能够满足前后端传输模型的需求,所以我们又建了DO、BO、DTO等模型来方便数据的传输,但是他们之间往往又会进行转换,下面是一个任意两个模型相互转换的工具类:
public class MyBeanUtils {
public static String[] getNullPropertyNames(Object source) {
final BeanWrapper src = new BeanWrapperImpl(source);
PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set<String> emptyNames = new HashSet<>();
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 void copyNotNullProperties(Object source, Object target) {
String[] ignoreProperties = getNullPropertyNames(source);
BeanUtils.copyProperties(source, target, ignoreProperties);
}
}
调用:
MyBeanUtils.copyNotNullProperties(xxxDto,xxxDo);
MyBeanUtils.copyNotNullProperties(xxxDo,xxxBo);