javabean和map相互轉換的例子

1. javabean轉map

 /**
     * javabean轉map, map的key爲小寫
     *
     * @param bean
     * @return
     * @throws Exception
     */
    private static Map<String, String> beanToMap(Object bean) throws Exception {
        Map<String, String> map = new HashMap<String, String>(16);
        //獲取bean的描述器
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(), Object.class);
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        //對屬性迭代
        for (PropertyDescriptor pd : pds) {
            //屬性名稱
            String propertyName = pd.getName();
            //獲取屬性值,用getter方法獲取
            Method method = pd.getReadMethod();
            Object properValue = method.invoke(bean);
            //map的key轉小寫
            map.put(propertyName.toLowerCase(), (String) properValue);
        }
        return map;
    }
}

 

2. map轉bean

//把Map轉化爲JavaBean
public static <T> T map2bean(Map<String,Object> map,Class<T> clz) throws Exception{
    //創建一個需要轉換爲的類型的對象
    T obj = clz.newInstance();
    //從Map中獲取和屬性名稱一樣的值,把值設置給對象(setter方法)

    //得到屬性的描述器
    BeanInfo b = Introspector.getBeanInfo(clz,Object.class);
    PropertyDescriptor[] pds = b.getPropertyDescriptors();
    for (PropertyDescriptor pd : pds) {
        //得到屬性的setter方法
        Method setter = pd.getWriteMethod();
        //得到key名字和屬性名字相同的value設置給屬性
        setter.invoke(obj, map.get(pd.getName()));
    }
    return obj;
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章