有時候,需要動態獲取對象的屬性值。
比如,給你一個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