Common-beanutils来封装map集合到实体类对象中

昨天碰到了一个问题在用common-beanutils的时候每次返回的值都是null

代码如下: System.out.println 为测试用

/**
     * 把map转化为指定类型的javabean 对象
     * @param map
     * @param clazz
     * @return 
     * @return
     */
    public static T toBean(Map map,Class clazz){

        try {
            /*
             * 创建指定类型的javabean对象
             */

            //System.out.println(map); 有值{Ben=whoami2, Ashin=whoami, Aken=whoami3}

            T bean =  clazz.newInstance();

            /*
             * 把数据封装到bean中
             */
            BeanUtils.populate(bean,map);
            //System.out.println(bean); //无值
            /*
             * 返回javabean对象
             */
            return bean;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

测试类:

@Test
    public void test(){
        Map<String,String> map = new HashMap<String,String>();
        map.put("username", "ashin");
        map.put("password", "whoami");
        /*关键点在这 昨天写的是put("ashin","whoami")
          map中的键要对应实体类中的属性 
          否则的话无法封装


        User user = CommonUtils.toBean(map, User.class);

        System.out.println(user);

如果有人和我遇到一样的问题希望能帮到你们~

你可能感兴趣的:(学习笔记)