Java反射获取对象VO的属性值(通过Getter⽅法)
有时候,需要动态获取对象的属性值。
⽐如,给你⼀个List,要你遍历这个List的对象的属性,⽽这个List⾥的对象并不固定。⽐如,这次User,下次可能是Company。
< 这次我需要做⼀个Excel导出的⼯具类,导出的批量数据是以List类型传⼊的,List⾥的对象⾃然每次都不同,这取决于需要导出什么信息。
为了使⽤⽅便,将对象的属性名与属性值存于Map当中,使⽤时就可以直接遍历Map了。
此次的思路是通过反射和Getter⽅法取得值,然后记录在⼀个Map当中。
将对象的属性名与属性值存于Map当中,以key,value的形式存在,⽽value并不希望以单⼀类型(如String)存在(因为涉及多种类型),所以⽤⼀个FieldEntity的⾃定义类(此类包含属性名,属性值,属性值类型等属性)
1package com.nicchagil.util.fields;
2
3
4import java.util.ArrayList;
5import java.util.List;
6
7public class FieldEntity {
8
9// field name
10private String fieldname;
11
12// field value
13private Object value;
14
15// field value's class type
16private Class clazz;
17
18private List<String> errorMsg = new ArrayList<String> ();
19
20public String getFieldname() {
21return fieldname;
22    }
23
24public void setFieldname(String fieldname) {
25this.fieldname = fieldname;
26    }
27
28public Object getValue() {
29return value;
30    }
31
32public void setValue(Object value) {
33this.value = value;
34    }
35
36public Class getClazz() {
37return clazz;
38    }
39
40public void setClazz(Class clazz) {
41this.clazz = clazz;
42    }
43
44public List<String> getErrorMsg() {
45return errorMsg;
46    }
47
48public void setErrorMsg(List<String> errorMsg) {
50    }
51
52public FieldEntity() {
53super();
54    }
56public FieldEntity(String fieldname, Object value, Class clazz) {
57super();
58this.fieldname = fieldname;
59this.value = value;
60this.clazz = clazz;
61    }
62
63private FieldEntity(String fieldname, List<String> errorMsg) {
64super();
65this.fieldname = fieldname;
67    }
68
69    @Override
70public String toString() {
71return "FieldEntity [fieldname=" + fieldname + ", value=" + value
72                + ", clazz=" + clazz + ", errorMsg=" + errorMsg + "]";
73    }
74
75 }
FieldEntity
主类,通过这个类的静态⽅法获取结果Map
1package com.nicchagil.util.fields;
2
3
4import flect.Field;
5import flect.InvocationTargetException;
6import flect.Method;
7import java.util.HashMap;
8import java.util.Map;
9
10public class FieldsCollector {
11
12public static Map<String, FieldEntity> getFileds(Object object)
13throws SecurityException, IllegalArgumentException, NoSuchMethodException,
14            IllegalAccessException, InvocationTargetException {
15        Class clazz = Class();
16        Field[] fields = DeclaredFields();
17        Map<String, FieldEntity> map = new HashMap<String, FieldEntity> ();
18
19for (int i = 0; i < fields.length; i++) {
20
21            Object resultObject = invokeMethod(object, fields[i].getName(), null);
22            map.put(fields[i].getName(), new FieldEntity(fields[i].getName(), resultObject, fields[i].getType()));
23        }
24
25return map;
26    }
27
28public static Object invokeMethod(Object owner, String fieldname,
29            Object[] args) throws SecurityException, NoSuchMethodException,
30            IllegalArgumentException, IllegalAccessException, InvocationTargetException {
31        Class ownerClass = Class();
32
33        Method method = null;
java反射的作用及应用场景
34        method = Getter(fieldname));
35
36        Object object = null;
37        object = method.invoke(owner);
38
39return object;
40    }
41
42 }
FieldsCollector
为了代码清楚些,将⼀些⼯具⽅法独⽴⼀下,如field name到getter name的转换⽅法
1package com.nicchagil.util.fields;
2
3public class GetterUtil {
5/**
6    * Get getter method name by field name
7    * @param fieldname
8    * @return
9*/
10public static String toGetter(String fieldname) {
11
12if (fieldname == null || fieldname.length() == 0) {
13return null;
14        }
15
16/* If the second char is upper, make 'get' + field name as getter name. For example, eBlog -> geteBlog */ 17if (fieldname.length() > 2) {
18            String second = fieldname.substring(1, 2);
19if (second.UpperCase())) {
20return new StringBuffer("get").append(fieldname).toString();
21            }
22        }
23
24/* Common situation */
25        fieldname = new StringBuffer("get").append(fieldname.substring(0, 1).toUpperCase())
26                .append(fieldname.substring(1)).toString();
27
28return  fieldname;
29    }
30
31 }
GetterUtil
⼤功告成!!!
现在,写个VO作为模拟数据
1import java.util.Date;
2
3public class User {
4
5private String username;
6private String password;
7private String eBlog;
8private Date registrationDate;
9
10public String getUsername() {
11return username;
12    }
13
14public void setUsername(String username) {
15this.username = username;
16    }
17
18public String getPassword() {
19return password;
20    }
21
22public void setPassword(String password) {
23this.password = password;
24    }
25
26public String geteBlog() {
27return eBlog;
28    }
29
30public void seteBlog(String eBlog) {
31this.eBlog = eBlog;
32    }
33
34public Date getRegistrationDate() {
35return registrationDate;
36    }
37
38public void setRegistrationDate(Date registrationDate) {
40    }
41
42 }
User
最后,测试类,此类将直接调⽤FieldsCollector~~
1import java.util.Date;
2import java.util.Map;
3
4import com.nicchagil.util.fields.FieldEntity;
5import com.nicchagil.util.fields.FieldsCollector;
6
7
8
9public class Call {
10
11public static void main(String[] args) throws Exception {
12
13        User user = new User();
14        user.setUsername("user109");
15        user.setPassword("pwd109");
16        user.seteBlog("wwwblogs/nick-huang/");
17        user.setRegistrationDate(new Date());
18
19        Map<String, FieldEntity> map = Fileds(user);
20        System.out.println(map);
21
22    }
23
24 }
Call
Oh year,成功了~~~

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。