关于BeanUtils.populate()方法的疑问?

今天在写代码的时候,有一个注册页面regist.html,里面的表单项除了用户名、密码、邮箱等待,最后还有一个验证码。而在RegistUserServlet中用了BeanUtils来封装成user对象。

 //1.获取数据
        Map<String, String[]> map = request.getParameterMap();
        //2.封装成对象
        User user=new User();
        try {
            BeanUtils.populate(user,map);
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }

于是我就有了疑惑:request获取的map集合中还有验证码这些没用的信息,那BeanUtils.populate()方法是如何把map中的数据封装成user的呢?不会报错吗?

去网上搜了一下这个方法才明白:

BeanUtils.populate( Object bean, Map properties ):

这个方法会遍历map<key, value>中的key,如果bean中有这个属性,就把这个key对应的value值赋给bean的属性。

感觉java语言真的很厉害。

原文地址:https://www.cnblogs.com/iceywu/p/12296556.html