Beanutils用了魔术般的反射技术实现了很多夸张有用的功能都是C/C++时代不敢想的无论谁的项目始终一天都会用得上它我算是后知后觉了第一回看到它的时候居然错过 属性的动态gettersetter 在这框架满天飞的年代不能事事都保证执行gettersetter函数了有时候属性是要根据名字动态取得的就像这样 BeanUtilsgetProperty(myBeancode); 而Common BeanUtils的更强功能在于可以直接访问内嵌对象的属性只要使用点号分隔 BeanUtilsgetProperty(orderBean addresscity); 相比之下其他类库的BeanUtils通常都很简单不能访问内嵌的对象所以有时要用Commons BeanUtils来替换它们 BeanUtils还支持List和Map类型的属性如下面的语法即可取得Order的顾客列表中第一个顾客的名字 BeanUtilsgetProperty(orderBean customers[]name); 其中BeanUtils会使用ConvertUtils类把字符串转为Bean属性的真正类型方便从HttpServletRequest等对象中提取bean或者把bean输出到页面 而PropertyUtils就会原色的保留Bean原来的类型 BeanCompartor 动态排序 还是通过反射动态设定Bean按照哪个属性来排序而不再需要在实现bean的Compare接口进行复杂的条件判断 List peoples = ; // Person对象的列表 Collectionssort(peoples new BeanComparator(age)); 如果要支持多个属性的复合排序如Order By lastNamefirstName ArrayList sortFields = new ArrayList(); sortFieldsadd(new BeanComparator(lastName)); sortFieldsadd(new BeanComparator(firstName)); ComparatorChain multiSort = new ComparatorChain(sortFields); Collectionssort(rowsmultiSort); 其中ComparatorChain属于jakata commonscollections包 如果age属性不是普通类型构造函数需要再传入一个comparator对象为age变量排序 另外 BeanCompartor本身的ComparebleComparator 遇到属性为null就会抛出异常 也不能设定升序还是降序这个时候又要借助commonscollections包的ComparatorUtils Comparator mycmp = ComparableComparatorgetInstance(); mycmp = ComparatorUtilsnullLowComparator(mycmp); //允许null mycmp = ComparatorUtilsreversedComparator(mycmp); //逆序 Comparator cmp = new BeanComparator(sortColumn mycmp); Converter 把Request或ResultSet中的字符串绑定到对象的属性 经常要从requestresultSet等对象取出值来赋入bean中如果不用MVC框架的绑定功能的话下面的代码谁都写腻了 String a = requestgetParameter(a); beansetA(a); String b = beansetB(b); 不妨写一个Binder自动绑定所有属性: MyBean bean = ; HashMap map = new HashMap(); Enumeration names = requestgetParameterNames(); while (nameshasMoreElements()) { String name = (String) namesnextElement(); mapput(name requestgetParameterValues(name)); } BeanUtilspopulate(bean map); 其中BeanUtils的populate方法或者getPropertysetProperty方法其实都会调用convert进行转换 但Converter只支持一些基本的类型甚至连javautilDate类型也不支持而且它比较笨的一个地方是当遇到不认识的类型时居然会抛出异常来对于Date类型我参考它的sqldate类型实现了一个Converter而且添加了一个设置日期格式的函数 要把这个Converter注册需要如下语句 ConvertUtilsBean convertUtils = new ConvertUtilsBean(); DateConverter dateConverter = new DateConverter(); convertUtilsregister(dateConverterDateclass); //因为要注册converter所以不能再使用BeanUtils的静态方法了必须创建BeanUtilsBean实例 BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtilsnew PropertyUtilsBean()); beanUtilssetProperty(bean name value); 其他功能 ConstructorUtils动态创建对象 public static Object invokeConstructor(Class klass Object arg) MethodUtils动态调用方法MethodUtilsinvokeMethod(bean methodName parameter); PropertyUtils当属性为CollectionMap时的动态读取Collection: 提供index BeanUtilsgetIndexedProperty(orderBeanitems); 或者BeanUtilsgetIndexedProperty(orderBeanitems[]); Map: 提供Key ValueBeanUtilsgetMappedProperty(orderBean items);//keyvalue goods_no= 或者BeanUtilsgetMappedProperty(orderBean items()) PropertyUtils直接获取属性的Class类型
public static Class getPropertyType(Object bean String name) |