《Jakarta Commons cookbook读书笔记》系列文章
2.2 org.apache.commons.beanutils.BeanComparator比较Bean属性
排序前
Book book
|--List authors
|--[0]->Person person1
|--String name->"LiLei"
|--[1]->Person person2
|--String name->"Ark"
|--[2]->Person person3
|--String name->"HanMeimei"
Comparator nameComparor=new BeanComparator("name"); Collections.sort(book.getAuthors(),nameComparor);
排序后
Book book
|--List authors
|--[0]->Person person1
|--String name->"Ark"
|--[1]->Person person2
|--String name->"HanMeimei"
|--[2]->Person person3
|--String name->"LiLei"
2.3 org.apache.commons.beanutils.collections.BeanMap 使用Map封装Bean
封装属性
Person person=new Person(); person.setName("Heis"); person.setAge(50); Map beanMap=new BeanMap(person); Map beanMap |--Entry(key->"name",value->"Heis") |--Entry(key->"age",value->Integer(50))
getReadMethod(),getWriteMethod()取读方法与写方法
BeanMap beanMap=new BeanMap(person); Method wMethod=beanMap.getWriteMethod("age"); wMethod.invoke(person,new Integer(24)); Method rMethod=beanMap.getReadMethod("age"); rMethod.invoke(person);->24
2.4 使用org.apache.commons.beanutils.DynaBean接口,可以在运行时创建动态Bean,而且创建的动态bean可以与BeanUtils包内的工具(如PropertyUtils等)结合使用。
DynaProperty[] beanProperties=new DynaProperty[]{ new DynaProperty("name",String.class), new DynaProperty("age",Integer.class)}; //BasicDynaBean implements DynaBean BasicDynaClass personClass=new BasicDynaClass("person",BasicDynaBean.class,beanProperties); DynaBean person=BasicDynaClass.newInstance(); //set the properties person.set("name","Heis"); PropertyUtils.setProperty(person,"age",new Integer(50));
2.5 使用BeanUtils以字符串形式访问属性
String ageStr=BeanUtils.getProperty(person,"age"); BeanUtils.setProperty(person,"age","50");