一個普通的實體Person:
1
2
3
4
5
6
7
|
private int id; private String name; private Date createdTime; ... //其它字段 // get set方法 ............... |
現在需要把通過webService傳過來的實體Person里面的所有字段的null值,換成""
實現思路:
1.獲取實體的所有字段,遍歷
2.獲取字段類型
3.調用字段的get方法,判斷字段值是否為空
4.如果字段值為空,調用字段的set方法,為字段賦值
code:
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
|
Field[] field = model.getClass().getDeclaredFields(); // 獲取實體類的所有屬性,返回Field數組 try { for ( int j = 0 ; j < field.length; j++) { // 遍歷所有屬性 String name = field[j].getName(); // 獲取屬性的名字 name = name.substring( 0 , 1 ).toUpperCase() + name.substring( 1 ); // 將屬性的首字符大寫,方便構造get,set方法 String type = field[j].getGenericType().toString(); // 獲取屬性的類型 if (type.equals( "class java.lang.String" )) { // 如果type是類類型,則前面包含"class ",后面跟類名 Method m = model.getClass().getMethod( "get" + name); String value = (String) m.invoke(model); // 調用getter方法獲取屬性值 if (value == null ) { m = model.getClass().getMethod( "set" +name,String. class ); m.invoke(model, "" ); } } if (type.equals( "class java.lang.Integer" )) { Method m = model.getClass().getMethod( "get" + name); Integer value = (Integer) m.invoke(model); if (value == null ) { m = model.getClass().getMethod( "set" +name,Integer. class ); m.invoke(model, 0 ); } } if (type.equals( "class java.lang.Boolean" )) { Method m = model.getClass().getMethod( "get" + name); Boolean value = (Boolean) m.invoke(model); if (value == null ) { m = model.getClass().getMethod( "set" +name,Boolean. class ); m.invoke(model, false ); } } if (type.equals( "class java.util.Date" )) { Method m = model.getClass().getMethod( "get" + name); Date value = (Date) m.invoke(model); if (value == null ) { m = model.getClass().getMethod( "set" +name,Date. class ); m.invoke(model, new Date()); } } // 如果有需要,可以仿照上面繼續進行擴充,再增加對其它類型的判斷 } } 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(); } |
感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!