Jakarta Commons Cookbook讀書筆記系列
2 Apache Commons BeanUtils 1.7
功能說(shuō)明:顧名思義,Bean Utility就是Bean小工具,主要是封裝了反射(reflection)和自省(introspection)的API(可以查看java.lang.reflect和java.beans文檔),對(duì)bean進(jìn)行操作。
主要功能:操作Bean的屬性,針對(duì)Bean屬性排序,Bean和Map的轉(zhuǎn)換,創(chuàng)建動(dòng)態(tài)的Bean等
2.1 org.apache.commons.beanutils.PropertyUtils 利用反射操作bean的屬性
getSimpleProperty()通過(guò)反射讀取屬性
Person person=new Person();
person.setName=("heis");
String name=(String)PropertyUtils.getSimpleProperty(person,"name");->heis
getNestedProperty()檢索嵌套的bean屬性
Book book=new Book();
book.setAuthor(person);
String authorName=(String)PropertyUtils.getNestedProperty(book,"author.name");//得到person的name
getIndexedProperty()訪問(wèn)數(shù)組或List型內(nèi)Object的屬性
Chapter chapter1=new Chapter();
Chapter chapter2=new Chapter();
book.getChapters().add(chapter1);
book.getChapters().add(chapter2);
Chapter chapter=(Chapter)PropertyUtils.getIndexedProperty(book,"chapter[0]");
getMappedProperty()訪問(wèn)Map型bean屬性的值
Person person=new Person();
person.setName=("heis");
Map favorites=new HashMap();
favorites.put("food","rice");
person.setFavorite(favorites);
String favorFood=(String)PropertyUtils.getMappedProperty(person,"favorites(food)");->rice
getProperty()和setProperty()可以訪問(wèn)任何bean屬性,通過(guò)表達(dá)式可以完成上面方法的功能
這是一個(gè)樹型的Bean屬性視圖
Book book
|--List authors
|--[0]->Person person
|--Map favorites
|--Entry(key->"food",value->"")
PropertyUtils.setProperty(book,"authors[0].favorites(food)","rice");
String favorFood=(String)PropertyUtils.getProperty(book,"authors[0].favorites(food)");->rice
isReadable()和isWritable()檢查bean是否可讀(有g(shù)etter)或可寫(有setter)
PropertyUtils.isReadable(book,"name");
PropertyUtils.isWritable(book,"name");
getPropertyType()獲取屬性類型
System.out.println(PropertyUtils.getPropertyType(person,"favorites"));->java.util.Map
copyProperty()復(fù)制Bean屬性,只復(fù)制引用,final類型和原始類型(primitive type)
Book book1=new Book();
book1.setName("Commons Cookbook Notes");
Book book2=new Book();
PropertyUtils.copyProperty(book2,book1);//將book1的name屬性copy到book2
describe()創(chuàng)建包含Bean屬性的Map
Person person=new Person();
person.setName("heis");
Book book=new Book();
book.setName("Commons Cookbook Notes");
book.setAuthor(person);
Map propMap=PropertyUtils.describe(book);
propMap.get("name");->Commons Cookbook Notes
propMap.get("author");->person
Jakarta Commons Cookbook讀書筆記系列
程序員的一生其實(shí)可短暫了,這電腦一開一關(guān),一天過(guò)去了,嚎;電腦一開不關(guān),那就成服務(wù)器了,嚎……