org.apache.commons.beanutils.PropertyUtils使用

2911 ワード

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