------- android培训、java培训、期待与您交流! ----------
Sun公司的内省API过于繁琐,所以Apache组织结合很多实际开发中的应用场景开发了一套简单、易用的API操作Bean的属性——BeanUtils,在Beanutil中可以直接进行类型的自动转换。
BeanUtils工具包下载:
1,登录http://commons.apache.org/beanutils/
2, 点击Download
3,点击Commons BeanUtils 1.8.3-bin.zip进行下载就OK了
使用BeanUtil
把commons-beanutils-1.8.3.jar包拷贝到项目目录下,选中它,点右键-->Build Path-->Add To Build Path即可。
BeanUtil的应用
Beanutils工具包的常用类:
1,BeanUtils
2,PropertyUtils
3,ConvertUtils.regsiter(Converter convert, Class clazz)
4,自定义转换器
导入BeanUtils包后,运行出错如下:
Exception in thread "main" java.lang.NoClassDefFoundError:org/apache/commons/logging/LogFactory
at org.apache.commons.beanutils.ConvertUtilsBean.<init>(ConvertUtilsBean.java:157)
at org.apache.commons.beanutils.BeanUtilsBean.<init>(BeanUtilsBean.java:117)
at org.apache.commons.beanutils.BeanUtilsBean$1.initialValue(BeanUtilsBean.java:68)
at org.apache.commons.beanutils.ContextClassLoaderLocal.get(ContextClassLoaderLocal.java:153)
at org.apache.commons.beanutils.BeanUtilsBean.getInstance(BeanUtilsBean.java:80)
at org.apache.commons.beanutils.BeanUtils.getProperty(BeanUtils.java:382)
at fighting.IntroSpectorDemo.main(IntroSpectorDemo.java:31)
因为BeanUtils包经常与common-logging包一起使用。
common-logging工具包下载:
1,登录http://commons.apache.org/proper/commons-logging/
2, 点击Download
3,点击commons-logging-1.1.3-bin.zip进行下载就OK了
使用common-logging
把commons-beanutils-1.8.3.jar包拷贝到项目目录下,选中它,点右键-->Build Path-->Add To Build Path即可。
这样再次运行就不会报错了!!
设置属性:
BeanUtils.setProperty(pt1, ”x“, "9");
BeanUtils.setProperty(pt1, "birthday.time", "111");//birthday是Date类型的属性,可以这样赋值
获取属性:
BeanUtils.getProperty(pt1, ”x“);
BeanUtils.getProperty(pt1, "birthday.time");
另外,还有一个类PropertyUtils也可以对属性进行操作。
PropertyUtils.setProperty(pt1, "x", 11);
System.out.println(PropertyUtils.getProperty(pt1, "x"));注意:PropertyUtils以属性本身的类型进行操作;BeanUtils是以字符串的形式对javabean进行操作的;所以如果使用PropertyUtils时,属性是int类型的,就不能像这样PropertyUtils.setProperty(pt1, "x", ”11“);给x的值加上引号了。