反射

場景:將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;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章