javaBean與map互轉

博客當筆記用、挺好。

1、map轉javabean


    //map轉javaBean
    public static <T>  T mapTobean(Map<String,Object> beanMap, Class<T> beanType) throws Exception {
        T obj = beanType.newInstance();

        BeanInfo beanInfo = Introspector.getBeanInfo(beanType, Object.class);
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
        for (PropertyDescriptor pd : pds) {
            String  propertyName = pd.getName();//屬性名
            Object propertyValue = beanMap.get(propertyName);//屬性值
            pd.getWriteMethod().invoke(obj,propertyValue);
        }
        return obj;
    }

2、javaBean轉map

 //javaBean轉Map
    public static Map<String,Object> beanToMap(Object bean) throws Exception {
        Map<String,Object> map = new HashMap<String, Object>();
        BeanInfo beanInfo = Introspector.getBeanInfo(bean.getClass(),Object.class);//獲取Bean中屬性名和屬性值
        PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();//獲取屬性描述對象數組
        for (PropertyDescriptor pd : pds) {
            String propertyName = pd.getName();//屬性名
            Object propertyValue = pd.getReadMethod().invoke(bean);//調用該屬性的get方法
            map.put(propertyName, propertyValue);
        }
        return map;
    }

 

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