Apache Commons BeanUtils 使用教程

碼頭工人 13年前發布 | 55K 次閱讀 Java Java開發

功能說明: 顧名思義,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) </span></p>

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
</span></span></strong></span></span>

 本文由用戶 碼頭工人 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!