Tải bản đầy đủ - 0 (trang)
Chapter 1. Supplements to the Java 2 Platform

Chapter 1. Supplements to the Java 2 Platform

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

Recipe1.16.CreatinganEnum

Recipe1.17.GeneratingUniqueNumericIdentifiers

Recipe1.18.ValidationofMethodParameters

Recipe1.19.MeasuringTime



Introduction

ThischapterintroducesutilitiesthataugmenttheJava2

StandardEdition(J2SE),providingclassesandutilitiesthat

makesomeofthemoremundaneprogrammingtasksmore

straightforward.JakartaCommonsLangisacollectionofuseful

supplementstotheJ2SE.Thispackagefillsgapspresentinthe

standardJavaAPIandprovidesanumberofsimple,timesavingutilityclasses.Sun'sJavadocforthejava.langpackage

intheJ2SEstatesthatthepackage"providesclassesthatare

fundamentaltothedesignoftheJavaprogramminglanguage."

Inthesamevein,JakartaCommonsLangprovidesclassesthat

augmentthefundamentaldesignoftheJavaprogramming

language.

Youmaybetemptedtoskipthesimplerecipespresentedinthis

chapterandcontinueontomoreadvancedtopicsinthistext.

Stringmanipulation,datetruncation,andtoString()

methodsdonotinspirethesenseofmysteryandgeniusone

feelswhenworkingwithExtensibleMarkupLanguage(XML)or

anopensourcetext-to-speechengine.But,evenifyouarethe

mostfluentspeakerofJava,therearelessonstobelearned

fromtheutilitiesintroducedinthischapter;asimpletrick

learnedheremaysaveyouafewminuteseverysingleday.

Don'twasteyourtimerewritingandmaintainingutilitiesthat

alreadyexistinCommonsLang;therearemoreinteresting

problemstobesolved,andbuildinghashcode()functionsisnot

oneofthem.



TheAdventofTiger

WiththereleaseofTiger(thecodenameforJava1.5),someoftheseutilitiesare

duplicatedorsuperseded.Thoseofyouwhoarestuckwith1.4forafewmore

monthswillfindsomeofthesupplementsinthischapterhelpful,regardlessof

theavailabilityofanewJavaVirtualMachine(JVM).EvenifyouareusingJava

1.5,therecipesinthischapterwillstillberelevant.Afewclassesinmany

JakartaCommonsprojectshavebeenmadeobsoletebythereleaseof1.4,but

therearestillmanyvocaluserswhoareusinganapplicationthatonlyrunsin

1.3(oreven1.2).Thebarforbackwardcompatibilitywilleventuallyshift,butfor

now,mostCommonscomponentsworkwith1.3or1.4ataminimum.



Recipe1.1ObtainingCommonsLang

Problem

YouwanttouseCommonsLangbecauseyourprogramneedsto

usesomeofthesimpleutilitiesthiscomponentprovides,such

asarraymanipulation,datemanipulation,andenums.



Solution

TodownloadthelatestversionofCommonsLang,followthese

steps:

1. Inawebbrowser,opentheURL

http://jakarta.apache.org/site/binindex.cgi.ThisURLwill

selectamirror,andgenerateapagewithlinkstodownload

binarydistributionsfromanApachemirror.

2. FindtheCommonsLangprojectsection.Ifyousearchfor

theterm"CommonsLang,"youwillfindasectionthat

providesalinktodownloadthelatestbinaryreleaseof

CommonsLang.

3. Clickoneitherthe2.0zipor2.0tar.gz(dependingonyour

platform)todownloadCommonsLang2.0.

4. Unziporuntarthebinarydistribution.Thiswillcreatea

directorynamedcommons-lang-2.0.Thecommons-lang-2.0

directoryshouldnowcontainaJavaArchive(JAR)file,

commons-lang-2.0.jar.

5. Copyoraddcommons-lang-2.0.jartoyourclasspath.



Discussion

Step#5variesbasedonyourdevelopmentenvironment.Ifyou

areworkingwithApacheAntasabuildtool,youwillneedto

makesurethatyourclasspathincludestheCommonsLangJAR.

IfyouareusinganIntegratedDevelopmentEnvironment(IDE)

likeEclipse,youwillneedtocopythisJARtoadirectoryinyour

project,andalteryourproject'spreferencestoaddCommons

Lang2.0tothe"JavaBuildPath."IfyouareusingMavenasa

buildtool,addthefollowingdependencytothedependencies

sectionofyourproject.xml:





commons-lang

2.0





...otherdependencies...





TheCommonsLanglibraryincludesutilitiesforworkingwith

dates,exceptions,arrays,enums,andmore.Itisoneofthe

mostwidelyusedlibrariesinopensourceJava.Tolearnmore

aboutCommonsLang,visittheJakartaCommonsLangwebsite

athttp://jakarta.apache.org/commons/lang/.



Atthetimeofwriting,themostrecentversionoftheCommonsLang

componentwasVersion2.0.Ifthereisamorerecentversionof

CommonsLangavailable,usethelatestversion.Althoughnota

guaranteeorapromise,mostJakartaCommonscomponentsstrivefor

backwardcompatibility.Ifaninterfacehasbeenalteredorfunctionality

removed,itwillbenotedinthereleasenotesforanewerversion.If

youaregoingtouseadifferentversionoftheCommonsLang

componentwiththerecipesinthischapter,makesuretoreadthe

releasenotes,whicharestoredinthefileRELEASE-NOTES.txt.



SeeAlso

IfyouarehavinganissuewithoneoftheutilitiesinCommons

Lang,seeRecipe1.2onjoiningtheCommons-usermailinglist.

Ifyouarelookingforthesourcecode,seeRecipe1.3on

obtainingthesourcecodeforCommonsLang.Youcanalsovisit

theCommonsLangwebsiteat

http://jakarta.apache.org/commons/lang.



Recipe1.2JoiningtheCommons-UserMailing

List

Problem

YouwanttoaskaquestionaboutacomponentinJakarta

Commons.



Solution

Jointhecommons-user@jakarta.apache.orgmailinglist,and

askyourquestion.ThismailinglistisfullofCommonsusers,

anditisagoodplacetodiscussanyproblemsyou'vehadwitha

particularutilityintheJakartaCommons.



Discussion

Beforeyoujointhismailinglist,takeamomenttofamiliarize

yourselfwiththemailinglistguidelinesavailableat

http://jakarta.apache.org/site/mail.html.Onceyouhaveread

theseguidelines,youcanfindinformationaboutjoiningthis

mailinglistat

http://jakarta.apache.org/site/mail2.html#Commons.

TheJakartaCommons-usermailinglistisaplaceforusersofall

Commonscomponentstoaskquestionsofotherusersand

Commonsdevelopers.Thismailinglisthasahighvolumeof

messages,andsubscribersshouldprefixallsubjectswiththe

componentyouarediscussing.InthecaseofCommonsLang,

makesureyouremailsubjectstartswith[lang]beforesending

amessagetotheCommons-usermailinglist;otherwise,your



emailmaybeignored.

Ifyouhaveaquestionoracomment,youwillsaveyourself

timeandtroubleifyousearchthearchivesoftheCommonsusermailinglist(http://www.mail-archive.com/commonsuser@jakarta.apache.org/)forrelateddiscussions.Thearchives

ofthismailinglistareagreatplacetolookifyouarehaving

problemswithaparticularCommonscomponent.Trynottoask

aquestionthathasalreadybeenaskedandansweredina

previousdiscussion,andrememberthattheApacheSoftware

Foundation(ASF)isavolunteerorganizationmembersofthe

communitywillgladlyassistyouifyouprovideenough

information.And,don'tbeshy.Ifyouknowtheanswerto

someone'squestion,youdon'thavetoaskforanyone's

permissiontoactivelyparticipate.



SeeAlso

TheCommons-usermailinglistarchiveisalsoavailablefrom

theEyebrowselistarchiveat

http://nagoya.apache.org/eyebrowse/SummarizeList?listId=15.



Recipe1.3GettingtheCommonsLangSource

Code

Problem

YouwanttoviewthesourcecodefortheCommonsLang

project.



Solution

Downloadthesourcecodefrom

http://jakarta.apache.org/site/sourceindex.cgi.Followingthe

sameprocedureasoutlinedinRecipe1.1,youcandownloada

filenamedcommons-lang-2.0-src.zip(orcommons-lang-2.0src.tar.gz).Onceyouunzipthisfile,youwillhavethesourceto

CommonsLangin./commons-lang-2.0-src.



Discussion

Thecommons-lang-2.0-srcdirectorywillcontainthefollowing:



build.xml

AnApacheAntbuildfile,whichyoucanusetocompilethe

source.IfAntisinstalled,youcancompileortestby

runningantcompileoranttest.



src/java

Thissubdirectorycontainsthesourcefortheclassesin

CommonsLang.



src/test

ThissubdirectorycontainsunittestsfortheCommonsLang

project.Each*Test.javafileisanextensionofJUnit

TestCaseclass.



SeeAlso

FormoreinformationaboutApacheAnt,seetheAntproject

pageathttp://ant.apache.org.AlsoseeChapter3intheJava

ExtremeProgrammingCookbookbyEricM.BurkeandBrianM.

Coyner(O'Reilly).

TheunittestsinthissourcedistributionusetheJUnittesting

framework.FormoreinformationaboutJUnit,seetheJUnit

projectpageathttp://www.junit.org.AlsoseeChapter4inthe

JavaExtremeProgrammingCookbookbyBurkeandCoyner.

SeeRecipe1.1forinformationaboutobtainingthebinary

distributionforCommonsLang,andseetheCommonsLang

websiteathttp://jakarta.apache.org/commons/lang.



Recipe1.4AutomatingtheGenerationof

toString()Content

Problem

YouwanttoautomatethecreationoftoString()methods.



Solution

UsetheCommonsLangReflectionToStringBuilderor

ToStringBuilderandToStringBuildertocreatetoString()

methods.ThefollowingcodeisanexampleofatoString()

method,whichusesareflectionbuilder:

importorg.apache.commons.lang.builder.ToStringBuilder;



publicvoidtoString(){

ReflectionToStringBuilder.toString(this);

}



Discussion

AssumethatyouhaveanobjectnamedPoliticalCandidatea

beanthatrepresentssomeinformationaboutapresidential



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

Chapter 1. Supplements to the Java 2 Platform

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

×