常用工具类BeanUtils

BeanUtils

BeanUtils的概述和简单使用

BeanUtils概述

BeanUtils是Apache commons组件的成员在之一,主要用于简化JavaBean封装数据的操作。它可以给JavaBean封装成一个字符串数据,也可以将一个表单提交的所有数据封装到JavaBean中。

需要的jar包

BeanUtils工具常用工具类有两个:BeanUtils,ConvertUtils。BeanUtils用于封装数据,ConvertUtils用于处理类型转换。

常用方法:
setProperty(Object obj,String name,Object value) 设置属性值,如果指定属性不存在,不抛异常。
getProperty(Object obj,String name) 获取属性值,如果指定属性不存在,抛方法找不到异常

代码案例:

public class BeanUtilsDemo {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        //Person persion = new Person("Jack", "22");


        Person person=new Person();
        System.out.println("封装前"+person);

        //使用BeanUtils的setProperty设置属性值
        BeanUtils.setProperty(person,"name","Jack");
        BeanUtils.setProperty(person,"age","22");
        System.out.println("封装后"+person);

        //使用BeanUtils的getProperty获取属性值
        System.out.println("name:"+BeanUtils.getProperty(person,"name"));
    }
}

运行结果:

封装前List.Person@677327b6
封装后List.Person@677327b6
name:Jack

BeanUtils的populate放的使用

方法说明

BeanUtils类的populated(Object bean,Map<String,String[]> properties):将Map数据封装到指定JavaBean中,一般用于将表单的所有数据封装到JavaBean中。

代码案例,使用populated方法将数据封装到User对对象中:

public class BeanUtilsDemo2 {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException {
        HashMap<String, String[]> map = new HashMap<String, String[]>();
        map.put("name",new String[]{"Jack"});
        map.put("age",new String[]{"22"});

        //使用populate方法进行填充
        Person person = new Person();
        BeanUtils.populate(person,map);

        System.out.println(person.getName()+":"+person.getAge());
    }
}

BeanUtils自定义工具类

自定义工具类的基本使用

自定义一个静态工具类,定义方法populate,参数为Object和Map<String,String[]>,返回值类型为void。方便自己在实际开发中使用。

代码案例:

public class PopulateDemo {
    public static Object populate(Class beanClass, Map<String,String[]> properties){
        Object bean=null;
        try {

            bean=beanClass.newInstance();
            BeanUtils.populate(bean,properties);
            return bean;
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
        return bean;
    }
}
  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值