List<map>转List<bean>

/**
     * 将 Map对象转化为JavaBean
     * @return Object对象
     */
    public static <T> T convertMap2Bean(Map map, Class T) throws Exception {
        if(map==null || map.size()==0){
            return null;
        }
        BeanInfo beanInfo = Introspector.getBeanInfo(T);
        T bean = (T)T.newInstance();
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        for (int i = 0, n = propertyDescriptors.length; i <n ; i++) {
            PropertyDescriptor descriptor = propertyDescriptors[i];
            String propertyName = descriptor.getName();
            if (map.containsKey(propertyName)) {
                Object value = map.get(propertyName);
                BeanUtils.copyProperty(bean, propertyName, value);
                
            }
        }
        return bean;
    }
 /**
     * 将 List<Map>对象转化为List<JavaBean>
     * @return Object对象
     */
    public static <T> List<T> convertListMap2ListBean(List<Map<String,Object>> listMap, Class T) throws Exception {
        List<T> beanList = new ArrayList<T>();
        for(int i=0, n=listMap.size(); i<n; i++){
            Map<String,Object> map = listMap.get(i);
            T bean = convertMap2Bean(map,T);
            beanList.add(bean);
        }
        return beanList;
    }


注意:实体字段类型为date时,会报类型转换的错误,解决方法搜:beanutil date 就有,因为我也没去试,所以就不贴代码了。

猜你喜欢

转载自blog.csdn.net/the_knife/article/details/76620608