例子
通过反射动态给对象赋值
@Test
public void testd() throws Exception {
Map<Object, Object> map = new HashMap<>();
map.put("name", "张三");
map.put("age", 18);
User user = new User();
reflectValue(map, user);
System.out.println(user.toString());
}
//通过反射动态给对象赋值
public Object reflectValue(Map<Object, Object> map, Object bean) throws Exception {
Class<?> cls = bean.getClass();
Method[] methods = cls.getDeclaredMethods();//获取该类所有的方法
Field[] fields = cls.getDeclaredFields();//获取该类所有的属性
for (Field field : fields) {
String fieldName = field.getName();
Object value = map.get(fieldName);
if (value == null) {
continue;
}
String setMethod = "set" + fieldName.substring(0, 1).toUpperCase() + fieldName.substring(1);
if (!checkMethod(setMethod, methods)) {
continue;
}
Method method = cls.getMethod(setMethod, field.getType());
method.setAccessible(true);//关闭安全检查
method.invoke(bean, value);
}
return bean;
}
//检查方法是否存在
private boolean checkMethod(String setMethod, Method[] methods) {
for (Method m : methods) {
if (setMethod.equals(m.getName())) {
return true;
}
}
return false;
}