场景:将query类中有值的属性封装成map
public Map queryToMap(Query query){
Map map = new HashMap();
Class<?> clz = query.getClass();
Field[] declaredFields = clz.getDeclaredFields();
for(int i=0; i<declaredFields.length; i++){
Method method;
try {
method = clz.getMethod("get" + getMethodName(declaredFields[i].getName()));
Object invoke = method.invoke(query);
//如果当前字段为null或者空字符串,则不加入参数集合
if(invoke != null && !"".equals(invoke)){
map.put(declaredFields[i].getName(), invoke);
}
// System.out.println("属性:" + declaredFields[i].getName() + ",值是:" + invoke);
// System.out.println(map.toString());
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return map;
}