妙用Commons良药 <五>

这一篇文章主要是讲一下关于Commons开源项目中其Commons BeanUtils的一些相关的用法.

1、复制Bean属性
如果你有两个相同的Bean的实例,并需要将其中的一个bean属性复制到另一个中去,调用PropertyUtils.copyProperties()即可,这一个方法经常在使用struts,hibernate等框架的时候常常用到.举例:
import org.apache.commons.beanutils.PropertyUtils;

Book book = new Book( );
book.setName( "Prelude to Foundation" );
book.setAuthorName( "Asimov" );
Book destinationBook = new Book( );
PropertyUtils.copyProperties( destinationBook, book );

请注意,该方法是将相同的引用对象赋给目的的bean,并没有克隆bean属性的值.


2、怎样使用Map来封装Bean
假如你需要将bean的属性传入Map
可使用BeanMap类封装任何Bean。该Map通过内省机制提供了对bean属性的访问,使得其看上去像是Map中成对的键与值.举例:
import java.util.*;
import org.apache.commons.beanutils.PropertyUtils;

// Create a Person and a Book bean instance
Person person = new Person( );
person.setName( "Some Dude" );

Book book = new Book( );
book.setName( "Some Silly Computer Book" );
book.setAuthor( person );

// Describe both beans with a Map
Map bookMap = PropertyUtils.describe( book );
Map authorMap = PropertyUtils.describe( bookMap.get("book") );
System.out.println( "Book Name: " + bookMap.get( "name" ) );
System.out.println( "Author Name: " + authorMap.get( "name" ) );

注意一点,如果你修改了BeanMap的时候,你也就修改了其内部的Bean.
还有常用的clear(),setBean(Object bean)等方法


3、可以根据Bean的属性来比较Beans
使用BeanComparator可根据bean属性来比较两个Bean.兴例如下:
import java.util.*;
import org.apache.commons.beanutils.BeanComparator;

Country country1 = new Country( );
country1.setName( "India" );
Country country2 = new Country( );
country2.setName( "Pakistan" );
Country country3 = new Country( );
country3.setName( "Afghanistan" );

// Create a List of Country objects
Country[] countryArray = new Country[] { country1, country2, country3 };
List countryList = Arrays.asList( countryArray );

// Sort countries by name
Comparator nameCompare = new BeanComparator( "name" );
Collections.sort( countryList, nameCompare );

System.out.println( "Sorted Countries:" );
Iterator countryIterator = countryList.iterator( );
while( countryIterator.hasNext( ) ) {
    Country country = (Country) countryIterator.next( );
    System.out.println( "\tCountry: " + country.getName( ) );
}

结果显示如下:
引用
Sorted Countries:
    Country: Afghanistan
    Country: India
    Country: Pakistan


注:文章中的代码均来之<<Jakarta  Commons Cookbook>>一书第三章

你可能感兴趣的:(apache,bean,Hibernate,框架,struts)