項目中需要過濾前面表單頁面中傳過來的實體類的中的String類型變量的前后空格過濾,由於前幾天看過一個其他技術博客的的java反射講解,非常受益。於是,哈哈哈
public static <T> void modelTrim(T model){ Class<T> clazz = (Class<T>) model.getClass(); //獲取所有的bean中所有的成員變量 Field[] fields = clazz.getDeclaredFields(); for(int j=0;j<fields.length;j++){ //獲取所有的bean中變量類型為String的變量 if("String".equals(fields[j].getType().getSimpleName())){ try { //獲取get方法名 String methodName = "get"+fields[j].getName().substring(0, 1).toUpperCase() +fields[j].getName().replaceFirst("\\w", ""); Method getMethod = clazz.getDeclaredMethod(methodName); //打破封裝 getMethod.setAccessible(true); //得到該方法的值 Object methodValue = getMethod.invoke(model); //判斷值是否為空或者為null,非的話這過濾前后空格 if(methodValue != null && !"".equals(methodValue)){ //獲取set方法名 String setMethodName = "set"+fields[j].getName().substring(0, 1).toUpperCase() +fields[j].getName().replaceFirst("\\w", ""); //得到get方法的Method對象,帶參數 Method setMethod = clazz.getDeclaredMethod(setMethodName,fields[j].getType()); setMethod.setAccessible(true); //賦值 setMethod.invoke(model, (Object)String.valueOf(methodValue).trim()); } } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } } }
親自上面試用是好使的
下面還有一套,通過request,和實體類來封裝本人還未實驗,以后有機會再試試
/** * 保存數據 *@param request *@param dto *@throws Exception */ public static void setDTOValue(HttpServletRequest request, Object dto) throws Exception { if ((dto == null) || (request == null)) return; //得到類中所有的方法 基本上都是set和get方法 Method[] methods = dto.getClass().getMethods(); for (int i = 0; i < methods.length; i++) { try { //方法名 String methodName = methods[i].getName(); //方法參數的類型 Class[] type = methods[i].getParameterTypes(); //當時set方法時,判斷依據:setXxxx類型 if ((methodName.length() > 3) && (methodName.startsWith("set")) && (type.length == 1)) { //將set后面的大寫字母轉成小寫並截取出來 String name = methodName.substring(3, 4).toLowerCase() + methodName.substring(4); Object objValue = getBindValue(request, name, type[0]); if (objValue != null) { Object[] value = { objValue }; invokeMothod(dto, methodName, type, value); } } } catch (Exception ex) { throw ex; } } }
還可以參考一下其他人的博客:
https://www.cnblogs.com/whgk/p/6122036.html