Apache commons beanutils簡介和使用

來源:互聯網
上載者:User

標籤:apache   java   code   beanutils   

在一般的寫bean組件的時候,都必須要寫setter和getter方法,當然假如我們事先已經知道bean的相關屬性和方法,寫bean是比較簡單的,但是組件太多的時候,重複編寫經常是枯燥乏味令人厭煩的。但當有些時候我麼需要調用動態對象的屬性的時候,我們應該怎麼來設定和擷取對象的屬性呢?BeanUtils就可以協助我們來簡化解決這個問題。

     目前最新的版本是1.9.

 

在日常的開發中,下面類似的代碼應該是非常的眼熟。

DynaActionForm daf =(DynaActionForm)form ;

 

        User user = new User() ;

 

        user.setId( daf.getString("id" ) ) ;

 

        user.setPassword( daf.getString( "password " ) ) ;

 

        user.setUsername( daf.getString( "username") ) ;

…

類似的對象的各種屬性的傳遞,在代碼中非常常見,利用beanutils可以簡化這些工作。

用beanutils的話,效果可以參考:

BeanUtils.copyProperties(user, daf ) ;

 

利用Apache commons beanutils複製對象的代碼如下:

packagetest.ffm83.commons.beanutils;

 

import java.util.HashMap;

importorg.apache.commons.beanutils.BeanUtils;

/* 通過commons beanutils進行對象傳遞

 * 注意:直接進行Bean之間的clone 複製後的2個Bean的同一個屬性可能擁有同一個對象的ref,特別是對於屬性為類的情況下。

 * @author 範芳銘

 * */

public class BeanutilsUsage {

     public static void main( String[] args ) throws Exception{

         EasyBean bean = new EasyBean();

         bean.setName( "範芳銘" );

        System.out.println("目標對象名稱:" + BeanUtils.getProperty( bean,"name" ));

        HashMap map = new HashMap();

        map.put( "1","12120000" );

        map.put( "2","12130000" );

        BeanUtils.setProperty( bean,"telephone", map );

       

        EasyBean dest = new EasyBean();

        BeanUtils.copyProperties( dest, bean );

        System.out.println("...目標複製後名稱:" + BeanUtils.getProperty( dest,"name" ));

        System.out.println("...目標複製後電話:" + BeanUtils.getProperty( dest,"telephone(1)" ));

 

    }

}

 

運行後結果如下:

目標對象名稱:範芳銘

...目標複製後名稱:範芳銘

...目標複製後電話:12120000

 

Apache commons beanutils簡介和使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.