com.zys.mybatis.utils.BeanUtil Maven / Gradle / Ivy
package com.zys.mybatis.utils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.BeanWrapper;
import org.springframework.beans.BeanWrapperImpl;
import java.lang.reflect.Field;
import java.util.*;
/**
* @author zys
* @version 1.0
* @date 2020/10/21 18:44
*/
@Slf4j
public class BeanUtil {
/**
*
* @param source 源对象list
* @param target 目标对象
* @param
* @return
*/
public static List copyList(List extends Object> source, Class target){
List targets = new ArrayList<>();
try {
for (Object o : source) {
Object t = target.newInstance();
BeanUtils.copyProperties(o,t);
targets.add((T) t);
}
} catch (InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
return targets;
}
private static String[] getNullPropertyNames (Object source) {
return getNames(source,false);
}
/**
*
* @param obj 忽略的对象
* @param flag true 有值,false null
* @return
*/
private static String[] getNames(Object obj,Boolean flag){
final BeanWrapper src = new BeanWrapperImpl(obj);
java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();
Set emptyNames = new HashSet<>();
for(java.beans.PropertyDescriptor pd : pds) {
Object srcValue = src.getPropertyValue(pd.getName());
if (flag) {
if (srcValue != null) emptyNames.add(pd.getName());
}else {
if (srcValue == null) emptyNames.add(pd.getName());
}
}
String[] result = new String[emptyNames.size()];
return emptyNames.toArray(result);
}
private static String[] getPropertyNames(Object target){
return getNames(target,true);
}
/**
* 忽略源对象为空的属性
* @param src 源对象
* @param target 目标对象
*/
public static void copyPropertiesIgnoreNull(Object src, Object target){
BeanUtils.copyProperties(src, target, getNullPropertyNames(src));
}
public static T[] concat(T[] first, T[] second) {
T[] result = Arrays.copyOf(first, first.length + second.length);
System.arraycopy(second, 0, result, first.length, second.length);
return result;
}
private static String[] getNullPropertyNames(Object src, Object target){
return concat(getNullPropertyNames(src), getPropertyNames(target));
}
/**
* 通过反射获取对象某个属性的值
* @param object 对象
* @param fieldName 字段名称
* @return
*/
public static Object getValue(Object object,String fieldName){
Class> aClass = object.getClass();
try {
Field field = aClass.getDeclaredField(fieldName);
field.setAccessible(true);
return field.get(object);
} catch (NoSuchFieldException e) {
log.error("未找到字段:{}",fieldName);
} catch (IllegalAccessException e) {
log.error("获取值失败:{}",fieldName);
}
return null;
}
/**
* 复制源对象为空的属性 和 目标对象有值的属性
* @param src 源对象
* @param target 目标对象
*/
public static void copyPropertiesIgnoreNullAndIgnoreTargetValue(Object src, Object target){
BeanUtils.copyProperties(src, target, getNullPropertyNames(src,target));
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy