1.根据传入的对象生成Map集合
@Test
public void test02(){
User user = new User();
user.setId(1);
user.setName("Albert");
user.setSex("男");
try{
Map<String, Object> map = getFieldVlaue(user);
System.out.println("通过反射获取属性值:"+map);
}catch(Exception e) {
}
}
/**
* 利用反射生成map
* @param obj
* @return
* @throws Exception
*/
public static Map<String, Object> getFieldVlaue(Object obj) throws Exception {
Map<String, Object> mapValue = new HashMap<String, Object>();
Class<?> cls = obj.getClass();
Field[] fields = cls.getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
String strGet = "get" + name.substring(0, 1).toUpperCase() + name.substring(1, name.length());
Method methodGet = cls.getDeclaredMethod(strGet);
Object object = methodGet.invoke(obj);
String value = object != null ? object.toString() : "";
mapValue.put(name, value);
}
return mapValue;
}