com.feingto.cloud.kit.reflection.BeanConvertKit Maven / Gradle / Ivy
package com.feingto.cloud.kit.reflection;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeansException;
import org.springframework.beans.FatalBeanException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.Collection;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* Bean属性转换工具类
*
* @author longfei
*/
@Slf4j
public abstract class BeanConvertKit extends org.springframework.beans.BeanUtils {
/**
* 把Bean数据转换到另外一个类的对象中。
*
* @param source 数据源
* @param targetClass 目标对象的类
* @return 目标对象
*/
public static Object convert(Object source, Class> targetClass) {
if (source == null)
return null;
try {
Object target = targetClass.newInstance();
copyProperties(source, target);
return target;
} catch (InstantiationException e) {
log.error("Can't create Instance of Class:" + targetClass, e);
} catch (IllegalAccessException e) {
log.error("Can't access construct method of Class:" + targetClass, e);
}
return null;
}
/**
* 把Bean集合数据转换到另外一个类的集合对象中。
*
* @param sources 数据源集合
* @param targetClass 目标对象的类
* @return 目标对象
*/
public static Object convert(Collection> sources, Class> targetClass) {
if (sources == null)
return null;
return sources.stream()
.map(obj -> {
Object target = null;
try {
target = targetClass.newInstance();
copyProperties(obj, target);
} catch (InstantiationException e) {
log.error("Can't create Instance of Class:" + targetClass, e);
} catch (IllegalAccessException e) {
log.error("Can't access construct method of Class:" + targetClass, e);
}
return target;
})
.collect(Collectors.toList());
}
/**
* 把Bean数据转换到另外一个类的对象中,源对象的空值不转换。
*
* @param source 数据源
* @param target 目标对象
*/
public static void copyProperties(Object source, Object target) throws BeansException {
Stream.of(getPropertyDescriptors(target.getClass()))
.filter(targetPd -> targetPd.getWriteMethod() != null)
.forEach(targetPd -> {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null && sourcePd.getReadMethod() != null) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
// 判断value是否为空(这里也能进行一些特殊要求的处理,例如绑定时格式转换等等。)
if (value != null) {
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
} catch (Exception e) {
throw new FatalBeanException("Could not copy properties from source to target", e);
}
}
});
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy