Jakarta Commons Cookbook讀書筆記系列
2 Apache Commons BeanUtils 1.7
功能說明:顧名思義,Bean Utility就是Bean小工具,主要是封裝了反射(reflection)和自省(introspection)的API(可以查看java.lang.reflect和java.beans文檔),對bean進行操作。
主要功能:操作Bean的屬性,針對Bean屬性排序,Bean和Map的轉換,創建動態的Bean等
2.1 org.apache.commons.beanutils.PropertyUtils 利用反射操作bean的屬性
getSimpleProperty()通過反射讀取屬性
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()訪問數組或List型內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()訪問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()可以訪問任何bean屬性,通過表達式可以完成上面方法的功能
這是一個樹型的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是否可讀(有getter)或可寫(有setter)
PropertyUtils.isReadable(book,"name");
PropertyUtils.isWritable(book,"name");
getPropertyType()獲取屬性類型
System.out.println(PropertyUtils.getPropertyType(person,"favorites"));->java.util.Map
copyProperty()復制Bean屬性,只復制引用,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()創建包含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讀書筆記系列
程序員的一生其實可短暫了,這電腦一開一關,一天過去了,嚎;電腦一開不關,那就成服務器了,嚎……