Java 通過反射給實體類賦值操作
表單提交這個方法是挺方便的,但在java來說就顯得有些麻煩了,
怎么個麻煩呢,就是當你字段多的時候,你就得一個一個的獲取其對應的值,這樣代碼量就多了起來,其代碼量不說,維護也是一個問題。
所以就有了這樣一個類,只需把request和實體類對象傳進去就行了,
這樣就會得到一個有值的實體類對象
下面是代碼示例
import java.lang.reflect.Field; import java.lang.reflect.Method; import java.sql.Date; import java.sql.Timestamp; import java.text.SimpleDateFormat; import javax.servlet.http.HttpServletRequest; public class RequestHelper { /** * 把request請求的數據放到java對象中 */ public static <T> T getSingleRequest(HttpServletRequest request, Class<T> obj) { //創(chuàng)建實例 T instance = null; try { //獲取類中聲明的所有字段 Field[] fields = obj.getDeclaredFields(); //創(chuàng)建新的實例對象 instance = obj.newInstance(); //利用循環(huán) for (int i = 0; i < fields.length; i++) { //獲取字段的名稱 String name = fields[i].getName(); //把序列化id篩選掉 if (name.equals("serialVersionUID")) { continue; } //獲取字段的類型 Class<?> type = obj.getDeclaredField(name).getType(); // 首字母大寫 String replace = name.substring(0, 1).toUpperCase() + name.substring(1); //獲得setter方法 Method setMethod = obj.getMethod("set" + replace, type); //獲取到form表單的所有值 String str = request.getParameter(replace); if (str == null || "".equals(str)) { // 首字母小寫 String small = name.substring(0, 1).toLowerCase() + name.substring(1); str = request.getParameter(small); } //通過setter方法賦值給對應的成員變量 if (str != null && !"".equals(str)) { // ---判斷讀取數據的類型 if (type.isAssignableFrom(String.class)) { setMethod.invoke(instance, str); } else if (type.isAssignableFrom(int.class) || type.isAssignableFrom(Integer.class)) { setMethod.invoke(instance, Integer.parseInt(str)); } else if (type.isAssignableFrom(Double.class) || type.isAssignableFrom(double.class)) { setMethod.invoke(instance, Double.parseDouble(str)); } else if (type.isAssignableFrom(Boolean.class) || type.isAssignableFrom(boolean.class)) { setMethod.invoke(instance, Boolean.parseBoolean(str)); } else if (type.isAssignableFrom(Date.class)) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); setMethod.invoke(instance, dateFormat.parse(str)); } else if (type.isAssignableFrom(Timestamp.class)) { SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); setMethod.invoke(instance, new Timestamp(dateFormat.parse(str).getTime())); } } } } catch (Exception e) { // TODO: handle exception e.printStackTrace(); } //返回實體類對象 return instance; } }
補充知識:java反射對實體類取值和賦值,可以寫成通過實體類獲取其他元素的數據,很方便哦~~~
項目中需要過濾前面表單頁面中傳過來的實體類的中的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; } } }
以上這篇Java 通過反射給實體類賦值操作就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。
相關文章
SpringBoot前后端分離項目之打包、部署到服務器詳細圖文流程
作為后臺開發(fā),項目打包部署是經常性的操作,下面這篇文章主要給大家介紹了關于SpringBoot前后端分離項目之打包、部署到服務器的相關資料,文中通過代碼示例介紹的非常詳細,需要的朋友可以參考下2023-12-12Java編程synchronized與lock的區(qū)別【推薦】
互聯(lián)網信息泛濫環(huán)境下少有的良心之作!如果您想對Java編程synchronized與lock的區(qū)別有所了解,這篇文章絕對值得!分享給大家,供需要的朋友參考。不說了,我先學習去了。2017-10-10Java實現(xiàn)Word/Pdf/TXT轉html的實例代碼
本文主要介紹了Java實現(xiàn)Word/Pdf/TXT轉html的實例代碼,代碼簡單易懂,非常不錯,具有一定的參考借鑒價值,需要的朋友可以參考下2020-02-02java中對象的比較equal、Comparble、Comparator的區(qū)別
本文主要介紹了java中對象的比較equal、Comparble、Comparator的區(qū)別,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下2021-10-10