Apache BeanUtils工具包的使用

1、说明

  1. BeanUtils 是 Apache commons的组件之一,主要用于简化JavaBean封装数据的操作。它可以给JavaBean封装一个字符串数据,也可以将一个表单提交的所有数据封装到JavaBean中。BeanUtils工具可以方便下列javaBean操作:

    • beanUtils 可以便于对javaBean的属性进行赋值。

    • beanUtils 可以便于对javaBean的对象进行赋值。

    • beanUtils可以将一个MAP集合的数据拷贝到一个javabean对象中。

    • 数据类型转换:字符串类型转换为各种具体的数据类型(实现Converter接口)。

  2. BeanUtils包常用API有两个:

    • BeanUtils(用于数据封装的操作)
    • ConvertUtils(用于处理类型转换的操作)
  3. Beanutils工具的常用方法:

    方法 功能
    public void copyProperties (Object dest, Object orig) 把orig中的值copy到dest中。
    public Map **describe **(Object bean) 把Bean的属性值放入到一个Map里面。
    public void **populate **(Object bean, Map properties) 把properties里面的值放入bean中。
    public void setProperty (Object bean, String name, Object value) 设置Bean对象的名称为name的property的值为value。
    public String getProperty(Object bean, String name) 取得bean对象中名为name的属性的值。

2、使用

  1. 使用BeanUtils前需要导入两个jar包:

    • commons-beanutils.jar
    • commons-logging.jar

    可以到Apache基金会官网下载:http://commons.apache.org

  2. 实现代码示例:

    //新建一个bean对象
    Role role = new Role();
    
    //使用BeanUtils给对象成员赋值。
    BeanUtils.setProperty(role, "name", "Jack");
    BeanUtils.setProperty(role, "sex", "men");
    BeanUtils.setProperty(role, "occupation", "warrior");
    BeanUtils.setProperty(role, "weapon", "sword");
    
    //用BeanUtils获取对象成员
    String roleName = BeanUtils.getProperty(role, "name");
    String roleSex = BeanUtils.getProperty(role, "sex");
    String roleOccu = BeanUtils.getProperty(role, "occupation");
    String roleweap = BeanUtils.getProperty(role, "weapon");
    System.out.println("角色名:" +roleName);
    System.out.println("性别:" +roleSex);
    System.out.println("职业:" +roleOccu);
    System.out.println("武器:" +roleweap);
    
    //使用集合统一给对象赋值
    Map<String, String> map = new HashMap<String, String>();
    map.put("name", "杰克");
    map.put("sex", "男");
    map.put("occupation", "战士");
    map.put("weapon", "长剑");
    BeanUtils.populate(role, map);    //用集合赋值
    System.out.println("角色名:" +role.getName());
    System.out.println("性别:" +role.getSex());
    System.out.println("职业:" +role.getOccupation());
    System.out.println("武器:" +role.getWeapon());
    
posted @ 2021-08-14 19:49  DvLopr_Jarjack  阅读(316)  评论(0)    收藏  举报