public class ReflectionUtils {
private ReflectionUtils() {
}
private static Logger logger = Logger.getLogger(ReflectionUtils.class);
public static void copyProperties(Map<String, String> sourceMap, Object targetObject) {
if (CollectionUtils.isEmpty(sourceMap)) {
return;
}
Class<? extends Object> clazz = targetObject.getClass();
/**
* 获取实体类的所有属性信息,返回Field数组;
*
* getFields()只能获取public的字段,包括父类的;
* getDeclaredFields()只能获取自己声明的各种字段,包括public,protected,private,但不包括父类的申明字段;
**/
Field[] fields = clazz.getDeclaredFields();
Map<String, Field> fieldMap = new HashMap<String, Field>();
for (Field field : fields) {
fieldMap.put(field.getName(), field);
}
try {
for (Entry<String, String> entry : sourceMap.entrySet()) {
if (fieldMap.containsKey(entry.getKey())) {
// 获取指定字段
Field field = fieldMap.get(entry.getKey());
field.setAccessible(true);
Class<?> fieldType = field.getType();
logger.debug("Key:" + entry.getKey() + " , Type:" + fieldType + " , Value:" + entry.getValue());
if (String.class == fieldType) {
field.set(targetObject, entry.getValue());
} else if (Boolean.class == fieldType) {
field.setBoolean(targetObject, Boolean.valueOf(entry.getValue()));
} else if (Integer.class == fieldType) {
field.set(targetObject, 10);
} else if (Double.class == fieldType) {
field.set(targetObject, Double.valueOf(entry.getValue()));
} else if (Long.class == fieldType) {
field.set(targetObject, Long.valueOf(entry.getValue()));
} else if (BigDecimal.class == fieldType) {
if (StringUtils.isNotBlank(entry.getValue())) {
field.set(targetObject, new BigDecimal(entry.getValue()));
}
} else if (Float.class == fieldType) {
field.set(targetObject, Float.valueOf(entry.getValue()));
} else {
logger.warn("****** 不支持的数据类型:" + entry.getKey() + " : " + fieldType);
}
}
}
} catch (SecurityException | IllegalArgumentException | IllegalAccessException e) {
logger.error(e);
}
}
}
ReflectionUtils
最新推荐文章于 2023-11-14 11:38:38 发布