Tải bản đầy đủ - 0 (trang)
Recipe 3.8 Accessing a Simple, Nested, Indexed, and Mapped Bean Property

Recipe 3.8 Accessing a Simple, Nested, Indexed, and Mapped Bean Property

Tải bản đầy đủ - 0trang

Mapcities=newHashMap();

cities.put("richmond",richmond);



RegionmidAtlantic=newRegion();

midAtlantic.setName("Mid-Atlantic");

midAtlantic.setCities(cities);



Listregions=newArrayList();

regions.add(midAtlantic);



Countrycountry=newCountry();

country.setName("UnitedStates");

country.setRegions(regions);



//RetrievethepopulationofRichmond

Longpopulation=

(Long)PropertyUtils.getProperty(country,



"regions[0].cities(richmond).po



Mostofthiscodesetsupacomplexnestedobjecthierarchyto

bequeriedbyPropertyUtils.getProperty().Retrievingthe

regions[0].cities(richmond).populationpropertyisthe

equivalentoftraversingdownatreeofobjectsandretrieving

thebottom-mostelementpopulation.



Discussion

TheemphasizedcoderetrievesthepopulationoftheCity

objectrichmond;itisequivalenttothefollowingcodeexcerpt:

Regionregion=(Region)country.getRegions().get(0);

Citycity=(City)region.getCities().get("Richmond");

Longpopulation=city.getPopulation();



Figure3-5displaysthestructureofthesethreebeans:

Country,Region,andCity.



Figure3-5.TheCountry,Region,andCitybeans



Whenaccessingabeanproperty,youcanuse

PropertyUtils.getProperty()inlieuofthemethods



introducedinthepreviousfourrecipes.ThegetProperty()

methodparsesthesuppliedpropertyname,splittingthename

astheperiodcharacter.Oncethispropertyhasbeensplit,this

utilityparseseachtokenandpassesthestringtothe

appropriatemethodgetSimpleProperty(),

getNestedProperty(),getIndexedProperty(),or

getMappedProperty().



SeeAlso

Beanpropertiesmayalsoberetrievedusingasimple

expressionlanguage,suchasExpressionLanguage(EL)orJava

ExpressionLanguage(JEXL).Formoreinformationabout

retrievingbeanpropertiesusinganexpressionlanguage,see

Recipe12.1.

BeanpropertiesmayalsoberetrievedusinganXPath

expression.Formoreinformation,seeRecipe12.1.



Recipe3.9DeterminingtheTypeofaBean

Property

Problem

Youneedtodeterminethetypeofabeanproperty.



Solution

UsePropertyUtils.getPropertyType()todeterminethe

typeofabeanproperty.ThisutilitywillreturnaClassobject

thatrepresentsthereturntypeoftheproperty'sgettermethod.

Thefollowingexampleusesthismethodtoobtainthereturn

typefortheauthorpropertyontheBookbean:

importorg.apache.commons.beanutils.PropertyUtils



Bookbook=newBook();



Classtype=PropertyUtils.getPropertyType(book,"author");



System.out.println("book.authortype:"+type.getName());



Thisexampleretrievesanddisplaysthetypeoftheauthor



propertyonBook,whichhappenstobeaPersonobject.The

typeofthepropertyisreturnedandprintedtotheconsole:

book.authortype:org.test.Person



Discussion

PropertyUtils.getPropertyType()alsoworksforacomplex

beanproperty.Passinganested,indexed,ormappedbean

propertytothisutilitywillreturnthetypeofthelastproperty

specified.Thefollowingcoderetrievesthetypeofanested,

indexedpropertychapters[0].name:

importorg.apache.commons.beanutils.PropertyUtils;



Chapterchapter=newChapter();

chapter.setName("Chapter3BeanUtils");

chapter.setLength(newInteger(40));



Listchapters=newArrayList();

chapters.add(chapter);



Bookbook=newBook();



book.setName("JakartaCommonsCookbook");

book.setAuthor("Dude");

book.setChapters(chapters);



Stringproperty="chapters[0].name";



ClasspropertyType=PropertyUtils.getPropertyType(book,proper



System.out.println(property+"type:"+propertyType.getName



Thiscoderetrievesthetypeofthenamepropertyfroman

instanceoftheChapterretrievedasanindexedproperty,andit

printsthefollowingoutput:

chapters[0].nametype:java.lang.String



PropertyUtilscontainsanothermethodtoretrievea

PropertyDescriptor-PropertyUtils.getPropertyDescriptor().Thismethod

takesareferencetoanybeanproperty,simpleorcomplex,and

returnsanobjectdescribingthetypeofapropertyand

providingaccesstothereadandwritemethodsofaproperty.

ThefollowingcodeexcerptobtainsthePropertyDescriptorof

anested,indexedpropertychapters[0].name:

Stringproperty="chapters[0].name";



PropertyDescriptordescriptor=

PropertyUtils.getPropertyDescriptor(book,property);



ClasspropertyType=descriptor.getPropertyType();

MethodwriteMethod=descriptor.getWriteMethod();

MethodreadMethod=descriptor.getReadMethod();



Recipe3.10ComparingBeans

Problem

Youneedtosortorcomparebeansbyabeanproperty.



Solution

UseBeanComparatortocomparetwobeansusingabean

property,whichcanbesimple,nested,indexed,ormapped.

BeanComparatorobtainsthevalueofthesamebeanproperty

fromtwoobjectsand,bydefault,comparesthepropertieswith

aComparableComparator.Thefollowingexamplesortsalistof

CountryobjectsusingaBeanComparatorandthedefault

ComparableComparator:

importjava.util.*;

importorg.apache.commons.beanutils.BeanComparator;



Countrycountry1=newCountry();

country1.setName("India");



Countrycountry2=newCountry();

country2.setName("Pakistan");



Countrycountry3=newCountry();

country3.setName("Afghanistan");



//CreateaListofCountryobjects



Country[]countryArray=newCountry[]{country1,country2,co

ListcountryList=Arrays.asList(countryArray);



//Sortcountriesbyname

ComparatornameCompare=newBeanComparator("name");

Collections.sort(countryList,nameCompare);



System.out.println("SortedCountries:");

IteratorcountryIterator=countryList.iterator();

while(countryIterator.hasNext()){

Countrycountry=(Country)countryIterator.next();

System.out.println("\tCountry:"+country.getName());

}



ThiscodecreatesthreeCountryobjectswithdifferentnames,

placestheCountryobjectsintoalist,andsortsthislistwitha

BeanComparatorconfiguredtocomparebythebeanproperty

name.Thiscodeexecutesandprintsthesortedlistofcountries:

SortedCountries:

Country:Afghanistan

Country:India

Country:Pakistan



Discussion

Thepreviousexampledemonstratedthedefaultbehaviorof

BeanComparator;whenaBeanComparatorisconstructedwith

onlyoneparameter,itusesaComparableComparatorto

comparethevaluesofthepropertiesitretrieves.Youcanalso

constructaBeanComparatorwithaninstanceofComparator;in

thiscase,BeanComparatordecoratesanotherComparator,

retrievingthevaluesofapropertyandpassingthesevalueson

toaninstanceofComparator.Thefollowingexample

demonstratestheuseofBeanComparatorwithacustom

Comparatorimplementation.Thisexampleinvolvestwoobjects

showninFigure3-6:ElectricVehicleandEngine.



Figure3-6.Objectsinvolvedinasortingexample



AnapplicationneedstosortElectricVehicleobjectsby

efficiency,and,inthiscontrivedexample,efficiencyisdefined

asthenumberofmilespergallontimesthepercentageof

electricoperation;an80%electrichybridvehicleismore

efficientthana25%electrichybridvehiclewiththesame

mileagebecauseofreducedemissions.Thecodefragments

showninExample3-5sortacollectionofbeansbywrappinga

customComparatorwithaBeanComparator.



Example3-5.DecoratingaComparatorwitha

BeanComparator

importjava.util.*;

importorg.apache.commons.beanutils.BeanComparator;



//CreateEngines

Engineengine1=newEngine();

engine1.setMilesGallon(newInteger(60));

engine1.setPercentElectric(newInteger(50));



Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Recipe 3.8 Accessing a Simple, Nested, Indexed, and Mapped Bean Property

Tải bản đầy đủ ngay(0 tr)

×