package reflect;import java.lang.reflect.Field;import java.lang.reflect.InvocationTargetException;import java.util.Date;import java.util.HashMap;import java.util.Map;import org.apache.commons.beanutils.BeanUtils;import org.apache.commons.beanutils.PropertyUtils;public class BeanUtilsTest {public static void printObj(Object o) throws IllegalArgumentException, IllegalAccessException{for(Field f:A.class.getDeclaredFields()){//getFields()不能擷取私人變數f.setAccessible(true);//暴力訪問private System.out.println(f.get(o));}}public static void properties(Object o) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{BeanUtils.setProperty(o, "birthDay.year", "113");//類屬性級聯設定//age是int型 這裡賦String 會自動轉換為Int 很適用於Web項目//如果是PropertyUtils.setProperty 就不會自動轉換BeanUtils.setProperty(o, "age", "27");System.out.println(BeanUtils.getProperty(o, "birthDay"));System.out.println(BeanUtils.getProperty(o, "age"));}public static void convertObjToMap(Object o) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException{Map map=BeanUtils.describe(o);for (Object key : map.keySet()) {System.out.println(key+":"+map.get(key));}}public static void putMapIntoObj(Object o) throws IllegalAccessException, InvocationTargetException{Map<String, Object> properties=new HashMap<String, Object>();properties.put("name", "rain");properties.put("age", "24");properties.put("birthDay", new Date());BeanUtils.populate(o, properties);//把Map的資料匯入ObjprintObj(o);//列印}public static void main(String[] args) throws IllegalAccessException, InvocationTargetException, NoSuchMethodException {A a=new A();BeanUtilsTest.printObj(a);//BeanUtilsTest.properties(a);//BeanUtilsTest.convertObjToMap(a);//BeanUtilsTest.putMapIntoObj(a);}}