map和bean转换

package com.test;

import java.util.HashMap;

import java.util.Map;

import java.util.Map.Entry;

import org.apache.commons.beanutils.BeanUtils;

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import com.pojo.User;

public class TestMapBeanConvert {

    private static Logger LOGGER = LoggerFactory.getLogger(TestMapBeanConvert.class);

    // 将map转为bean

    public staticT mapToBean(Map map, Class clz) {

        T bean = null;

        try {

              bean = clz.newInstance();

            // 遍历map中的key,若bean中有这个属性(key),将key对应的value赋值给bean对应的属性

            BeanUtils.populate(bean, map); // 将map转为bean

        } catch (Exception e) {

            LOGGER.info("ERROR ------> " + e.getMessage());

        }

        return bean;

    }

    // 将bean转为map

    public staticMapbeanToMap(Object bean) {

        Map map = null;

        try {

            map = BeanUtils.describe(bean); // 将bean转为map

        } catch (Exception e) {

              LOGGER.info("ERROR ------> " + e.getMessage());

       }

       return map;

       }

       public static void main(String[] args) {

              Map map = new HashMap();

              map.put("name", "六月");

              map.put("age",6);

              System.err.println("-------------------- from map to bean --------------------");

              User user = mapToBean(map, User.class);System.err.println(user.toString());

              System.err.println("-------------------- from bean to map --------------------");

              Map toMap = beanToMap(user);

              for(Entry entry:toMap.entrySet()){

                     System.out.println("key=" +entry.getKey() +" and value="+entry.getValue()); 

              } 

       }

}

你可能感兴趣的:(map和bean转换)