您的位置:首页 > 编程语言 > Java开发

java反射调用set和get方法的通用类

2018-04-02 13:44 567 查看

我们有一个类的字段非常多,当我们要给遍历它的值或者说给它赋值时,最笨的方法是 每一个字段去set和get。

 

这意味着我们可能要写几十个set和get。

 

那有没有更方便快捷的方法呢  

 

针对这种情况,我们前面已经  写了遍历的方法 也就是通过反射get属性名和属性值的 方法 : 

java中通过反射遍历属性字段及值

那set呢。

 

我们这次 找到了一个通用类,里面包含了set和get的方法:

1 package com.reallyinfo.ourea.util;
2
3 import java.lang.reflect.Field;
4 import java.lang.reflect.Method;
5 import java.text.SimpleDateFormat;
6 import java.util.Date;
7 import java.util.HashMap;
8 import java.util.Locale;
9 import java.util.Map;
10
11 public class BeanRefUtil {
12     /**
13      * 取Bean的属性和值对应关系的MAP
14      *
15      * @param bean
16      * @return Map
17      */
18     public static Map<String, String> getFieldValueMap(Object bean) {
19         Class<?> cls = bean.getClass();
20         Map<String, String> valueMap = new HashMap<String, String>();
21         Method[] methods = cls.getDeclaredMethods();
22         Field[] fields = cls.getDeclaredFields();
23         for (Field field : fields) {
24             try {
25                 String fieldType = field.getType().getSimpleName();
26                 String fieldGetName = parGetName(field.getName());
27                 if (!checkGetMet(methods, fieldGetName)) {
28                     continue;
29                 }
30                 Method fieldGetMet = cls.getMethod(fieldGetName, new Class[] {});
31                 Object fieldVal = fieldGetMet.invoke(bean, new Object[] {});
32                 String result = null;
33                 if ("Date".equals(fieldType)) {
34                     result = fmtDate((Date) fieldVal);
35                 } else {
36                     if (null != fieldVal) {
37                         result = String.valueOf(fieldVal);
38                     }
39                 }
40 //                String fieldKeyName = parKeyName(field.getName());
41                 valueMap.put(field.getName(), result);
42             } catch (Exception e) {
43                 continue;
44             }
45         }
46         return valueMap;
47     }
48
49     /**
50      * set属性的值到Bean
51      *
52      * @param bean
53      * @param valMap
54      */
55     public static void setFieldValue(Object bean, Map<String, String> valMap) {
56         Class<?> cls = bean.getClass();
57         // 取出bean里的所有方法
58         Method[] methods = cls.getDeclaredMethods();
59         Field[] fields = cls.getDeclaredFields();
60
61         for (Field field : fields) {
62             try {
63                 String fieldSetName = parSetName(field.getName());
64                 if (!checkSetMet(methods, fieldSetName)) {
65                     continue;
66                 }
67                 Method fieldSetMet = cls.getMethod(fieldSetName,
68                         field.getType());
69 //                String fieldKeyName = parKeyName(field.getName());
70                 String  fieldKeyName = field.getName();
71                 String value = valMap.get(fieldKeyName);
72                 if (null != value && !"".equals(value)) {
73                     String fieldType = field.getType().getSimpleName();
74                     if ("String".equals(fieldType)) {
75                         fieldSetMet.invoke(bean, value);
76                     } else if ("Date".equals(fieldType)) {
77                         Date temp = parseDate(value);
78                         fieldSetMet.invoke(bean, temp);
79                     } else if ("Integer".equals(fieldType)
80                             || "int".equals(fieldType)) {
81                         Integer intval = Integer.parseInt(value);
82                         fieldSetMet.invoke(bean, intval);
83                     } else if ("Long".equalsIgnoreCase(fieldType)) {
84                         Long temp = Long.parseLong(value);
85                         fieldSetMet.invoke(bean, temp);
86                     } else if ("Double".equalsIgnoreCase(fieldType)) {
87                         Double temp = Double.parseDouble(value);
88                         fieldSetMet.invoke(bean, temp);
89                     } else if ("Boolean".equalsIgnoreCase(fieldType)) {
90                         Boolean temp = Boolean.parseBoolean(value);
91                         fieldSetMet.invoke(bean, temp);
92                     } else {
93                         System.out.println("not supper type" + fieldType);
94                     }
95                 }
96             } catch (Exception e) {
97                 continue;
98             }
99         }
100     }
101
102     /**
103      * 格式化string为Date
104      *
105      * @param datestr
106      * @return date
107      */
108     public static Date parseDate(String datestr) {
109         if (null == datestr || "".equals(datestr)) {
110             return null;
111         }
112         try {
113             String fmtstr = null;
114             if (datestr.indexOf(':') > 0) {
115                 fmtstr = "yyyy-MM-dd HH:mm:ss";
116             } else {
117                 fmtstr = "yyyy-MM-dd";
118             }
119             SimpleDateFormat sdf = new SimpleDateFormat(fmtstr, Locale.UK);
120             return sdf.parse(datestr);
121         } catch (Exception e) {
122             return null;
123         }
124     }
125
126     /**
127      * 日期转化为String
128      *
129      * @param date
130      * @return date string
131      */
132     public static String fmtDate(Date date) {
133         if (null == date) {
134             return null;
135         }
136         try {
137             SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss",
138                     Locale.US);
139             return sdf.format(date);
140         } catch (Exception e) {
141             return null;
142         }
143     }
144
145     /**
146      * 判断是否存在某属性的 set方法
147      *
148      * @param methods
149      * @param fieldSetMet
150      * @return boolean
151      */
152     public static boolean checkSetMet(Method[] methods, String fieldSetMet) {
153         for (Method met : methods) {
154             if (fieldSetMet.equals(met.getName())) {
155                 return true;
156             }
157         }
158         return false;
159     }
160
161     /**
162      * 判断是否存在某属性的 get方法
163      *
164      * @param methods
165      * @param fieldGetMet
166      * @return boolean
167      */
168     public static boolean checkGetMet(Method[] methods, String fieldGetMet) {
169         for (Method met : methods) {
170             if (fieldGetMet.equals(met.getName())) {
171                 return true;
172             }
173         }
174         return false;
175     }
176
177     /**
178      * 拼接某属性的 get方法
179      *
180      * @param fieldName
181      * @return String
182      */
183     public static String parGetName(String fieldName) {
184         if (null == fieldName || "".equals(fieldName)) {
185             return null;
186         }
187         int startIndex = 0;
188         if (fieldName.charAt(0) == '_')
189             startIndex = 1;
190         return "get"
191                 + fieldName.substring(startIndex, startIndex + 1).toUpperCase()
192                 + fieldName.substring(startIndex + 1);
193     }
194
195     /**
196      * 拼接在某属性的 set方法
197      *
198      * @param fieldName
199      * @return String
200      */
201     public static String parSetName(String fieldName) {
202         if (null == fieldName || "".equals(fieldName)) {
203             return null;
204         }
205         int startIndex = 0;
206         if (fieldName.charAt(0) == '_')
207             startIndex = 1;
208         return "set"
209                 + fieldName.substring(startIndex, startIndex + 1).toUpperCase()
210                 + fieldName.substring(startIndex + 1);
211     }
212
213     /**
214      * 获取存储的键名称(调用parGetName)
215      *
216      * @param fieldName
217      * @return 去掉开头的get
218      */
219     public static String parKeyName(String fieldName) {
220         String fieldGetName = parGetName(fieldName);
221         if (fieldGetName != null && fieldGetName.trim() != ""
222                 && fieldGetName.length() > 3) {
223             return fieldGetName.substring(3);
224         }
225         return fieldGetName;
226     }
227
228 }

使用方法:

set的使用方法:

假设User是我们的自定义类:

1  package com.reallyinfo.ourea.core.io;
2
3 public class User {
4     private String username;
5     private String userpassword;
6
7     public String getUsername() {
8         return username;
9     }
10
11     public void setUsername(String username) {
12         this.username = username;
13     }
14
15     public String getUserpassword() {
16         return userpassword;
17     }
18
19     public void setUserpassword(String userpassword) {
20         this.userpassword = userpassword;
21     }
22
23 }

map中键装入类的字段名  值装入字段值:set方法

1 Map<String,String> map = new HashMap<String, String>();
2 map.put("username","joe");
3 map.put("userpassword","123456");
4 User   user = new User();
5 BeanRefUtil.setFieldValue(user, map);

get方法的使用:

1 Map<String, String> valueMap = BeanRefUtil.getFieldValueMap(user);

 

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: