BeanUtils–org.apache.commons.beanutils.BeanUtils

來源:互聯網
上載者:User
轉自: http://www.blogjava.net/huanzhugege/archive/2007/02/05/97964.htmlBeanUtils
BeanUtils是Apache-Commons項目提供的另一個非常方便的類庫,通過這個類庫能夠更方便的使用反射。最常用的類是BeanUtils(org.apache.commons.beanutils包中),使用這個類能通過名字訪問一個Bean中的某個屬性。
通過BeanUtils.getProperty(person,”age”)能得到person的age屬性。此方法還支援內嵌對象,比如BeanUtils.getProperty(person,”manager.name”)就能得到person的manager屬性的name屬性。還支援List和Map類型的屬性,如下面的文法即可取得Order的顧客列表中第一個顧客的名字BeanUtils.getProperty(orderBean, "customers[1].name")。 使用BeanUtils.setProperty方法則可以設定javaBean的屬性值。
ConstructorUtils提供了調用建構函式的方法,使用public static Object invokeConstructor(Class klass, Object arg)可以直接調用某個類的建構函式。
MethodUtils提供了調用bean方法的方法,使用MethodUtils.invokeMethod(bean, methodName, parameter);可以直接調用某個類的某個方法。
PropertyUtils提供了更詳細的屬性存取方法,使用public static Class getPropertyType(Object bean, String name)擷取屬性的Class類型。
UserInfo userInfo = (UserInfo) ConstructorUtils.invokeConstructor(
    UserInfo.class, new Object[] {});
PersonInfo personInfo = (PersonInfo) ConstructorUtils
    .invokeConstructor(PersonInfo.class, new Object[] {});
BeanUtils.setProperty(personInfo, "age", new Integer(20));
BeanUtils.setProperty(personInfo, "name", "Tom");
BeanUtils.setProperty(userInfo, "number", "admin");
  BeanUtils.setProperty(userInfo, "person", personInfo);
System.out.println(BeanUtils.getProperty(userInfo, "person.name"));
BeanUtils.setProperty(userInfo, "person.name","xdx");
System.out.println(BeanUtils.getProperty(userInfo, "person.name"));
System.out.println(PropertyUtils.getPropertyType(userInfo,"person"));
運行結果:
Tom
xdx
class com.cownew.PIS.basedata.common.PersonInfo--------------------------------------------------------------------- 

Beanutils用了魔術般的反射技術,實現了很多誇張有用的功能,都是C/C++時代不敢想的。無論誰的項目,始終一天都會用得上它。我算是後知後覺了,第一回看到它的時候居然錯過。

1.屬性的動態getter、setter

在這架構滿天飛的年代,不能事事都保證執行getter,setter函數了,有時候屬性是要根據名字動態取得的,就像這樣:  
BeanUtils.getProperty(myBean,"code");
而Common BeanUtils的更強功能在於可以直接存取內嵌對象的屬性,只要使用點號分隔。
BeanUtils.getProperty(orderBean, "address.city");
相比之下其他類庫的BeanUtils通常都很簡單,不能訪問內嵌的對象,所以有時要用Commons BeanUtils來替換它們。

BeanUtils還支援List和Map類型的屬性,如下面的文法即可取得Order的顧客列表中第一個顧客的名字

BeanUtils.getProperty(orderBean, "customers[1].name");
其中BeanUtils會使用ConvertUtils類把字串轉為Bean屬性的真正類型,方便從HttpServletRequest等對象中提取bean,或者把bean輸出到頁面。而PropertyUtils就會原色的保留Bean原來的類型。

2.BeanCompartor 動態排序

還是通過反射,動態設定Bean按照哪個屬性來排序,而不再需要在實現bean的Compare介面進行複雜的條件判斷。
List peoples = ...; // Person對象的列表Collections.sort(peoples, new BeanComparator("age"));

如果要支援多個屬性的複合排序,如"Order By lastName,firstName"

ArrayList sortFields = new ArrayList();sortFields.add(new BeanComparator("lastName"));sortFields.add(new BeanComparator("firstName"));ComparatorChain multiSort = new ComparatorChain(sortFields);Collections.sort(rows,multiSort);

其中ComparatorChain屬於jakata commons-collections包。
如果age屬性不是普通類型,建構函式需要再傳入一個comparator對象為age變數排序。
另外, BeanCompartor本身的ComparebleComparator, 遇到屬性為null就會拋出異常, 也不能設定升序還是降序。這個時候又要藉助commons-collections包的ComparatorUtils.

   Comparator mycmp = ComparableComparator.getInstance();
   mycmp = ComparatorUtils.nullLowComparator(mycmp);  //允許null
   mycmp = ComparatorUtils.reversedComparator(mycmp); //逆序
   Comparator cmp = new BeanComparator(sortColumn, mycmp);

3.Converter 把Request或ResultSet中的字串綁定到對象的屬性

   經常要從request,resultSet等對象取出值來賦入bean中,如果不用MVC架構的綁定功能的話,下面的代碼誰都寫膩了。

   String a = request.getParameter("a");   bean.setA(a);   String b = ....
bean.setB(b);
......

不妨寫一個Binder自動綁定所有屬性:

    MyBean bean = ...;    HashMap map = new HashMap();    Enumeration names = request.getParameterNames();    while (names.hasMoreElements())    {      String name = (String) names.nextElement();      map.put(name, request.getParameterValues(name));    }    BeanUtils.populate(bean, map);

    其中BeanUtils的populate方法或者getProperty,setProperty方法其實都會調用convert進行轉換。
    但Converter只支援一些基本的類型,甚至連java.util.Date類型也不支援。而且它比較笨的一個地方是當遇到不認識的類型時,居然會拋出異常來。 對於Date類型,我參考它的sqldate類型實現了一個Converter,而且添加了一個設定日期格式的函數。
要把這個Converter註冊,需要如下語句:

    ConvertUtilsBean convertUtils = new ConvertUtilsBean();
   DateConverter dateConverter = new DateConverter();
   convertUtils.register(dateConverter,Date.class);



//因為要註冊converter,所以不能再使用BeanUtils的靜態方法了,必須建立BeanUtilsBean執行個體
BeanUtilsBean beanUtils = new BeanUtilsBean(convertUtils,new PropertyUtilsBean());
beanUtils.setProperty(bean, name, value);

4 其他功能

4.1 ConstructorUtils,動態建立對象
     public static Object invokeConstructor(Class klass, Object arg)

4.2 MethodUtils,動態調用方法

    MethodUtils.invokeMethod(bean, methodName, parameter);

4.3 PropertyUtils,當屬性為Collection,Map時的動態讀取:
Collection: 提供index

   BeanUtils.getIndexedProperty(orderBean,"items",1);

或者

  BeanUtils.getIndexedProperty(orderBean,"items[1]");

Map: 提供Key Value

  BeanUtils.getMappedProperty(orderBean, "items","111");//key-value goods_no=111 

或者

  BeanUtils.getMappedProperty(orderBean, "items(111)") 

4.4 PropertyUtils,直接擷取屬性的Class類型
     public static Class getPropertyType(Object bean, String name)
4.5 動態Bean用DynaBean減除不必要的VO和FormBean 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.