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