BeanUtils工具包下载及应用

Sun公司的内省API过于繁琐,因此Apache组织结合不少实际开发中的应用场景开发了一套简单、易用的API操做Bean的属性——BeanUtils,在Beanutil中能够直接进行类型的自动转换。apache

BeanUtil工具包下载:ide

 1,登陆http://commons.apache.org/beanutils/工具

 2,  点击Downloadspa

 3, 点击Commons BeanUtils 1.8.3-bin.tar.gz进行下载就OK了orm

使用BeanUtil对象

在项目中导入commons-beanutils-1.8.3.jar包便可开发

BeanUtil的应用get

   Beanutils工具包的经常使用类:string

        1,BeanUtilsit

        2,PropertyUtils

        3,ConvertUtils.regsiter(Converter convert, Class clazz)

        4,自定义转换器

  在这里我举了几个不一样的实例:

Java代码   收藏代码
  1.  实例1代码:  

  2. publicvoid test1() throws Exception {  

  3. // 加载类

  4.        Class cls = Class.forName("cn.csdn.beanutil.Student");  

  5. // 建立对象

  6.        Student bean = (Student) cls.newInstance();  

  7. // 经过beanutil给name属性赋值

  8.        BeanUtils.setProperty(bean, "name", "wangli");  

  9.        Object obj = BeanUtils.getProperty(bean, "name");  

  10.        System.out.println(obj);  

  11.    }  

  12.       实例2代码:  

  13. publicvoid test2() throws Exception {  

  14.        Date da = new Date();  

  15. // 加载类

  16.        Class cls = Class.forName("cn.csdn.beanutil.Student");  

  17. // 建立对象

  18.        Student bean = (Student) cls.newInstance();  

  19. // 经过Beanutil给属性赋值

  20.        BeanUtils.setProperty(bean, "birthday", da);  

  21.        System.out.println(bean.getBirthday());  

  22.    }  

  23.      实例3代码:  

  24. publicvoid test4() throws Exception {  

  25. //建立对象

  26.        Student bean = new Student();  

  27. //经过ConvertUtils自动转换日期类型

  28.        ConvertUtils.register(new DateLocaleConverter(), Date.class);  

  29. //经过BeanUtils给属性赋值

  30.        BeanUtils.setProperty(bean, "birthday", "2003-10-30");  

  31. //执行

  32.        System.out.println(bean.getBirthday());  

  33.    }  

  34. 实例4代码:  

  35. //自定义转换器

  36. publicvoid test5() throws Exception{  

  37. //建立对象

  38.        Student bean = new Student();  

  39. //经过ConvertUtils自定义转换日期类型

  40.        ConvertUtils.register(new Converter() {  

  41. public Object convert(Class type, Object value) {  

  42. if (value == null) {  

  43. returnnull;  

  44.                } else {  

  45. //定义日期格式

  46.                SimpleDateFormat sdi = new SimpleDateFormat("yyyy-MM-dd");  

  47.                    Date dt = null;  

  48. try {  

  49.                        dt = sdi.parse((String) value);  

  50.                    } catch (ParseException e) {  

  51. //抛出异常

  52. thrownew ConversionException("日期格式转化不对.....");  

  53.                    }  

  54. return dt;  

  55.                }  

  56.            }  

  57.        }, Date.class);  

  58. //经过BeanUtils给属性赋值

  59.        BeanUtils.setProperty(bean, "birthday", "1990-13-33");  

  60. //执行

  61.        System.out.println(bean.getBirthday());  

  62.    }  

相关文章
相关标签/搜索