com.github.hetianyi.common.util.BeanUtil Maven / Gradle / Ivy
package com.github.hetianyi.common.util;
import org.apache.commons.beanutils.ConvertUtils;
import org.springframework.cglib.beans.BeanCopier;
/**
* Bean操作工具类
*
* @author Jason He
* @version 1.0.9
* @since 1.0.9
* @date 2020-02-20
*/
public class BeanUtil {
/**
* 将对象source的字段复制到target对应字段,
* target字段在source中对应不到的字段或者转换的失败的字段将赋值null。
* @param source 源对象
* @param target 目标对象
*/
public static T copyProperties(S source, T target) {
if (null == source || null == target) {
return target;
}
BeanCopier copier = BeanCopier.create(source.getClass(), target.getClass(), true);
copier.copy(source, target, (o, aClass, o1) -> {
if (null == o || aClass.isAssignableFrom(o.getClass())) {
return o;
}
Object ret = ConvertUtils.convert(o, aClass);
return (null != ret && aClass.isAssignableFrom(ret.getClass())) ? ret : null;
});
return target;
}
}
© 2015 - 2024 Weber Informatics LLC | Privacy Policy