import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
public class BeanUtils {
//忽略大小写且NULL值不会覆盖新值
public static <T> T copyProperties(Object source, Object target) {
Map<String, Field> sourceMap = CacheFieldMap.getFieldMap(source.getClass());
CacheFieldMap.getFieldMap(target.getClass()).values().forEach((it) -> {
Field field = sourceMap.get(it.getName().toLowerCase().replace("_", ""));
if (field != null) {
it.setAccessible(true);
field.setAccessible(true);
try {
//忽略null
if (field.get(source) != null) {
//修改全部使用场景为Integer类型赋值到String类型。若不需要则删除
if (field.get(source) instanceof Integer) {
it.set(target, field.get(source) + "");
} else {
it.set(target, field.get(source));
}
}
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
});
return (T) target;
}
private static class CacheFieldMap {
private static Map<String, Map<String, Field>> cacheMap = new HashMap<>();
private static Map<String, Field> getFieldMap(Class clazz) {
Map<String, Field> result = cacheMap.get(clazz.getName());
if (result == null) {
synchronized (CacheFieldMap.class) {
if (result == null) {
Map<String, Field> fieldMap = new HashMap<>();
for (Field field : clazz.getDeclaredFields()) {
fieldMap.put(field.getName().toLowerCase().replace("_", ""), field);
}
cacheMap.put(clazz.getName(), fieldMap);
result = cacheMap.get(clazz.getName());
}
}
}
return result;
}
}
}
BeanUtils.copyProperties方法忽略大小写
最新推荐文章于 2024-04-22 10:07:55 发布