表單提交這個方法是挺方便的,但在java來說就顯得有些麻煩了,
怎么個麻煩呢,就是當(dāng)你字段多的時候,你就得一個一個的獲取其對應(yīng)的值,這樣代碼量就多了起來,其代碼量不說,維護也是一個問題。
所以就有了這樣一個類,只需把request和實體類對象傳進去就行了,
這樣就會得到一個有值的實體類對象
下面是代碼示例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
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請求的數(shù)據(jù)放到j(luò)ava對象中 */ 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方法賦值給對應(yīng)的成員變量 if (str != null && ! "" .equals(str)) { // ---判斷讀取數(shù)據(jù)的類型 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反射對實體類取值和賦值,可以寫成通過實體類獲取其他元素的數(shù)據(jù),很方便哦~~~
項目中需要過濾前面表單頁面中傳過來的實體類的中的String類型變量的前后空格過濾,由于前幾天看過一個其他技術(shù)博客的的java反射講解,非常受益。于是,哈哈哈
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
|
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對象,帶參數(shù) 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,和實體類來封裝本人還未實驗,以后有機會再試試
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
|
/** * 保存數(shù)據(jù) *@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(); //方法參數(shù)的類型 Class[] type = methods[i].getParameterTypes(); //當(dāng)時set方法時,判斷依據(jù):setXxxx類型 if ((methodName.length() > 3 ) && (methodName.startsWith( "set" )) && (type.length == 1 )) { //將set后面的大寫字母轉(zhuǎn)成小寫并截取出來 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 通過反射給實體類賦值操作就是小編分享給大家的全部內(nèi)容了,希望能給大家一個參考,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/weixin_44578470/article/details/91355563