2005年11月30日星期三

Jakarta Commons BeanUtils的使用

MyBean bean = new MyBean();
String propertyName = "name";
String value = "mazhen";

Method setter = getWriteMethod(bean, propertyName);
if ( setter != null ) {
try {
setter.invoke(bean, new Object[]{value});
} catch (Exception ex) {
ex.printStaceTrace();
}
}
private Method getWriteMethod(Object bean, String name) {
BeanInfo beanInfo;
try {
beanInfo = Introspector.getBeanInfo(bean.getClass());
} catch (IntrospectionException ex) {
ex.printStackTrace();
throw new RuntimeException(ex);
}
PropertyDescriptor pds[] = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor pd : pds ) {
if ( pd.getName().equals(name) ) {
return pd.getWriteMethod();
}
}
return null;
}
难倒不难,就是比较麻烦。现在,我们有了Commons BeanUtils,一切都变得非常简单,而且功能更加强大。

1. 访问简单属性
String name = (String) PropertyUtils.getSimpleProperty( person, "name" );

2. 访问嵌套属性
Book book = new Book( );
book.setName( "Emerson's Essays" );

Person author = new Person( );
author.setName( "Ralph Waldo Emerson" );

book.setAuthor( author );

String authorName = (String) PropertyUtils.getNestedProperty(book, "author.name");

3. 访问索引属性
Book book = new Book( );
Chapter chapter1 = new Chapter( );
Chapter chapter2 = new Chapter( );

List chapters = new ArrayList( );
chapters.add( chapter1 );
chapters.add( chapter2 );

book.setChapters( chapters );

// You can retrieve the first chapters like this...

Chapter chapterOne = (Chapter) PropertyUtils.getIndexedProperty( book, "chapters[0]" );

// Or... you can retrieve the first chapter like this...

chapterOne = (Chapter) PropertyUtils.getIndexedProperty( book, "chapters", 0 );

4. 访问maped 属性
Room dining = new Room( );
dining.setArea( 20 );
dining.setCarpeted( true );
dining.setFurnished( true );

Map rooms = new HashMap( );
rooms.put( "Dining Room", dining );

Apartment apartment = new Apartment( );
apartment.setRooms( rooms );

// Retrieve the livingRoom key
Room room = (Room) PropertyUtils.getMappedProperty( apartment, "rooms(Dining Room)" );

// Or.. retrieve the livingRoom key with 3 parameters -

// equivalent to previous

room = (Room) PropertyUtils.getMappedProperty( apartment, "rooms", "Dining Room" );

5.访问简单、嵌套、索引和mapped属性

// Create a series of nested beans
City richmond = new City( );
richmond.setName( "Richmond" );
richmond.setPopulation( new Long(500000) );

Map cities = new HashMap( );
cities.put( "richmond", richmond );

Region midAtlantic = new Region( );
midAtlantic.setName( "Mid-Atlantic" );
midAtlantic.setCities( cities );

List regions = new ArrayList( );
regions.add( midAtlantic );

Country country = new Country( );
country.setName( "United States" );
country.setRegions( regions );

// Retrieve the population of Richmond
Long population = (Long) PropertyUtils.getProperty( country, "regions[0].cities(richmond).population" );

6. 决定属性的类型
Class type = PropertyUtils.getPropertyType( book, "author" );

7. 按照属性排序
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 );

8. copy属性
注意没有clone
Author author = new Author( );
author.setName( "Zinsser" );

Book book = new Book( );
book.setName( "On Writing Well" );

book.setAuthor( author );

Book destinationBook = new Book( );

PropertyUtils.copyProperties( destinationBook, book );

9. clone 一个Bean
Book book1 = new Book( );
book1.setName( "Count of Monte Cristo" );

Book book2 = (Book) BeanUtils.cloneBean( book1 );

10. 设置Bean的属性
Book book1 = new Book( );
book1.getChapters( ).add( new Chapter( ) );
book1.getChapters( ).add( new Chapter( ) );

PropertyUtils.setProperty( book1, "name", "Apache: The Definitive Guide" );
PropertyUtils.setProperty( book1, "author", new Person( ) );
PropertyUtils.setProperty( book1, "author.name", "Laurie" );
PropertyUtils.setProperty( book1, "chapters[0].name", "Introduction" );

Apartment apartment = new Apartment( );
apartment.getRooms( ).put( "livingRoom", new Room( ) );

PropertyUtils.setProperty( apartment, "rooms(livingRoom).length", new Integer(12) );

11. 检查属性的访问
boolean nameReadable = PropertyUtils.isReadable( book, "name" );
boolean nameWritable = PropertyUtils.isWritable( book, "name" );

12. Validating Beans with Predicates
// A Predicate that returns true if the "name" property is not null
Predicate teamNotNull = new BeanPredicate( "name", new NotNullPredicate( ) );

// A Predicate that returns true if the "coach.firstName" property is "Tom"
Predicate coachFirstName = new BeanPredicate( "coach.firstName", new EqualsPredicate("Tom") );

// Tie two Predicates together into an AndPredicate
Predicate validateTeam = new AllPredicate( predicateArray );

// Create Team Objects
Team fish = new Team( "Swordfish", new Coach( "Tom", "O'Connell") );
Team hens = new Team( "Hens", new Coach( "Bob", "McGarry") );

boolean fishValid = validateTeam.evaluate( fish );
boolean henValid = validateTeam.evaluate( hens );

13.Creating a Map of Bean Properties
// 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" ) );

14.Wrapping a Bean with a Map
Person person = new Person( );
person.setName( "Jim" );
person.setAge( new Integer( 28 ) );
person.setOccupation( "Developer" );

Map beanMap = new BeanMap( person );

Set keys = beanMap.keySet( );
Iterator keyIterator = keys.iterator( );
while( keyIterator.hasNext( ) ) {
String propertyName = (String) keyIterator.next( );
System.out.println( "Property: " + propertyName +
", Value: " + beanMap.get( propertyName ) +
", Type: " + beanMap.getType( propertyName ).
toString( ) );
}

15.Creating a Dynamic Bean
DynaProperty[] beanProperties = new DynaProperty[]{
new DynaProperty("name", String.class),
new DynaProperty("party", Party.class),
new DynaProperty("votes", Long.class)
};

BasicDynaClass politician new BasicDynaClass("politician", BasicDynaBean.class, props);

DynaBean politician = politicianClass.newInstance( );

// Set the properties via DynaBean
politician.set( "name", "Tony Blair" );
politician.set( "party", Party.LABOUR );
politician.set( "votes", new Long( 50000000 ) );

// Set the properties with PropertyUtils
PropertyUtils.setProperty( politician, "name", "John Major" );
PropertyUtils.setProperty( politician, "party", Party.TORY );
PropertyUtils.setProperty( politician, "votes", new Long( 50000000 ) );

16. 使用String设置或得到属性
Person person = new Person( );
person.setAge( new Integer( 45 ) );
person.setName( "Donald" );
person.setOccupation( "Salesman" );

// Get the Age as a String
String ageString = BeanUtils.getProperty( person, "age" );

// Set the Age from a String
BeanUtils.setProperty( person, "age", "50" );

2005年11月24日星期四

try to connect from TCP ports greater than 5000

http://support.microsoft.com/default.aspx?scid=kb;EN-US;196271