BeanUtils工具包下载及应用
Sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils,在Beanutil中可以直接进行类型的自动转换。
BeanUtil工具包下载:
1,登录http://commons.apache.org/beanutils/
2, 点击Download
3, 点击Commons BeanUtils 1.8.3-bin.tar.gz进行下载就OK了
使用BeanUtil
在项目中导入commons-beanutils-1.8.3.jar包即可
BeanUtil的应用
Beanutils工具包的常用类:
1,BeanUtils
2,PropertyUtils
3,ConvertUtils.regsiter(Converter convert, Class clazz)
4,自定义转换器
在这里我举了几个不同的实例:
实例1代码: public void test1() throws Exception { // 加载类 Class cls = Class.forName("cn.csdn.beanutil.Student"); // 创建对象 Student bean = (Student) cls.newInstance(); // 通过beanutil给name属性赋值 BeanUtils.setProperty(bean, "name", "wangli"); Object obj = BeanUtils.getProperty(bean, "name"); System.out.println(obj); } 实例2代码: public void test2() throws Exception { Date da = new Date(); // 加载类 Class cls = Class.forName("cn.csdn.beanutil.Student"); // 创建对象 Student bean = (Student) cls.newInstance(); // 通过Beanutil给属性赋值 BeanUtils.setProperty(bean, "birthday", da); System.out.println(bean.getBirthday()); } 实例3代码: public void test4() throws Exception { //创建对象 Student bean = new Student(); //通过ConvertUtils自动转换日期类型 ConvertUtils.register(new DateLocaleConverter(), Date.class); //通过BeanUtils给属性赋值 BeanUtils.setProperty(bean, "birthday", "2003-10-30"); //执行 System.out.println(bean.getBirthday()); } 实例4代码: //自定义转换器 public void test5() throws Exception{ //创建对象 Student bean = new Student(); //通过ConvertUtils自定义转换日期类型 ConvertUtils.register(new Converter() { public Object convert(Class type, Object value) { if (value == null) { return null; } else { //定义日期格式 SimpleDateFormat sdi = new SimpleDateFormat("yyyy-MM-dd"); Date dt = null; try { dt = sdi.parse((String) value); } catch (ParseException e) { //抛出异常 throw new ConversionException("日期格式转化不对....."); } return dt; } } }, Date.class); //通过BeanUtils给属性赋值 BeanUtils.setProperty(bean, "birthday", "1990-13-33"); //执行 System.out.println(bean.getBirthday()); }
BeanUtils工具包下载:下载附件。
<!--EndFragment-->