计算机专业文献翻译在 JDK 早期版本中使用 Java 5 的语言特性.docx
《计算机专业文献翻译在 JDK 早期版本中使用 Java 5 的语言特性.docx》由会员分享,可在线阅读,更多相关《计算机专业文献翻译在 JDK 早期版本中使用 Java 5 的语言特性.docx(11页珍藏版)》请在冰豆网上搜索。
计算机专业文献翻译在JDK早期版本中使用Java5的语言特性
UsingJava5languagefeaturesinearlierJDK
Java5addedanumberofpowerfullanguagefeatures:
generics,enumerations,annotations,autoboxing,andtheenhancedforloop.However,manyshopsarestilltiedtoJDK1.4orearlierandmaybeforsometimetocome.Butit'sstillbepossibleforthosedeveloperstotakeadvantageofthesepowerfullanguagefeatureswhilecontinuingtodeployonearlierJVMs.BrianGoetzreturnsfromhishiatusinthisinstallmentofJavatheoryandpracticetodemonstratehow.
WithJava6.0beingnewlyreleased,youmightthinktheJava5languagefeaturesare"oldnews."Butevennow,whenIaskdeveloperswhichversionoftheJavaplatformtheyareusingindevelopment,typicallyonlyhalfareusingJava5--andtheotherhalfarejealous.TheyareeagertousethelanguagefeaturesaddedinJava5suchasgenericsandannotations,butanumberoffactorsstillpreventmanyfromdoingso.
OnecategoryofdevelopersunabletotakeadvantageofJava5featuresarethosewhodevelopcomponents,libraries,orapplicationframeworks.BecausetheircustomersmaystillbeusingJDK1.4orearlierandclassescompiledwithJava5cannotbeloadedbyJDK1.4orpreviousJVMs,usingJava5languagefeatureswouldlimittheircustomerbasetocompaniesthathavealreadytransitionedtoJava5.
AnothergroupofdevelopersoftenheldbackfromusingJava5arethoseworkingwithJavaEE.ManyshopswillnotuseJava5withJavaEE1.4orearlierforfearthatitwillnotbesupportedbytheirapplicationservervendor.ButitmaybeawhilebeforethoseshopstransitiontoJavaEE5.InadditiontothelagtimebetweentheJavaEE5andJavaSE5specifications,commercialJavaEE5containersarenotnecessarilyavailableassoonastheinkisdryonthespecification,businessesdonotnecessarilyupgradetheirapplicationsserversassoonasthenextversionisavailable,andevenafterupgradingtheirapplicationserver,itmaytakesometimetocertifytheirapplicationsonthenewplatform.
Java5languagefeatureimplementation
ThelanguagefeaturesaddedinJava5--generics,enumerations,annotations,autoboxing,andtheenhancedforloop--requirednochangetotheJVMinstructionset,andarealmostentirelyimplementedinthestaticcompiler(javac)andclasslibraries.Whenthecompilerencounterstheuseofgenerics,itattemptstoverifythattypesafetyispreserved(emittingan"uncheckedcast"warningifitcannot)andthenemitsbytecodethatisidenticaltowhatwouldbeproducedfromequivalentnongenericcode,castsandall.Similarly,autoboxingandtheenhancedforlooparesimply"syntacticsugar"forequivalent,butmoreverbose,idioms,andenumerationsarecompiledintoordinaryclasses.
Intheory,youcouldtaketheclassfilesproducedbyjavacandloadtheminearlierJVMs,whichwas,infact,theintentionwhenJSR14(theJavaCommunityProcessworkinggroupresponsibleforgenerics)wasconvened.However,otherissues(suchasretentionofannotations)forcedtheclassfileversiontobechangedbetweenJava1.4andJava5,whichpreventscodecompiledforJava5tobeloadedbyearlierJVMs.Further,someofthelanguagefeaturesaddedinJava5havedependenciesontheJava5libraries.Ifyoucompileaclasswithjavac-target1.5andtrytoloaditonanearlierJVM,you'llgetanUnsupportedClassVersionErrorbecausethe-target1.5optiongeneratesclasseswithaclassfileversionof49,andJDK1.4onlysupportsclassfileversionsthrough48.
Thefor-eachloop
Theenhancedforloop,sometimescalledthefor-eachloop,istranslatedbythecompilerasiftheprogrammerhadsuppliedtheequivalentold-styleforloop.Thefor-eachloopcaniterateovertheelementsofanarrayorofacollection.Listing1showsthesyntaxofiteratingoveracollectionwiththefor-eachloop:
Listing1.Thefor-eachloop
CollectionfooCollection=...
for(Foof:
fooCollection){
doSomething(f);
}
Thecompilertranslatesthiscodeintotheequivalentiterator-basedloop,asshowninListing2:
Listing2.Iterator-basedequivalentforListing1
for(Iteratoriter=f.iterator();f.hasNext();){
Foof=(Foo)iter.next();
doSomething(f);
}
Howdoesthecompilerknowthatthesuppliedargumenthasaniterator()method?
Thearchitectsofthejavaccompilercouldhavebuiltinunderstandingofthecollectionsframework,butthisapproachwouldhavebeenunnecessarilyrestrictive.Instead,anewinterfacewascreated,java.lang.Iterable(seeListing3),andthecollectionclasseswereretrofittedtoimplementIterable.Thisway,containerclassesthatdonotbuildonthecorecollectionsframeworkcanstilltakeadvantageofthenewfor-eachloop.ButdoingsocreatesadependencyontheJava5classlibrarybecauseIterableisnotpresentintheJDK1.4library.
Listing3.TheIterableinterface
publicinterfaceIterable{
Iteratoriterator();
}
Enumerationsandautoboxing
Justlikethefor-eachloop,enumerationsrequiresupportfromtheclasslibrary.Whenthecompilerencountersanenumeratedtype,itgeneratesaclassthatextendsthelibraryclassjava.lang.Enum.But,justlikeIterable,theEnumclassisnotpresentintheJDK1.4classlibrary.
Similarly,autoboxingreliesonthevalueOf()methodsbeingaddedtotheprimitivewrapperclasses(suchasInteger).WhenboxingrequiresconversionfrominttoInteger,ratherthancallingnewInteger(int),thecompilergeneratesacalltoInteger.valueOf(int).TheimplementationofthevalueOf()methodsemploystheflyweightpatterntocachetheIntegerobjectsforcommonlyusedintegervalues(theJava6implementationcachesintegersfrom-128to127),whichmayimproveperformancebyeliminatingredundantinstantiations.And,justlikeIterableandEnum,thevalueOf()methodsarenotpresentintheJDK1.4classlibrary.
Varargs
Whenthecompilerencountersamethoddefinedwithavariable-lengthargumentlist,itconvertsitintoamethodthattakesanarrayoftheappropriatecomponenttype;whenthecompilerencountersacalltoamethodwithavariable-lengthargumentlist,itboxestheargumentsintoanarray.
Annotations
Whenanannotationisdefined,itcanbeannotatedwith@Retention,whichdetermineswhatthecompilerwilldowithclasses,methods,orfieldsthatpossessthatannotation.ThedefinedretentionpoliciesareSOURCE(discardannotationdataatcompilation),CLASS(recordannotationsintheclassfile),orRUNTIME(recordannotationsintheclassfileandretainthematruntimesotheycanbeaccessedreflectively).
Otherlibrarydependencies
PriortoJava5,whenthecompilerencounteredanattempttoconcatenatetwostrings,itusedthehelperclassStringBuffertoperformtheconcatenation.InJava5andlater,itinsteadgeneratescallstothenewStringBuilderclass,whichisnotpresentintheJDK1.4andearlierclasslibraries.
AccessingJava5features
Becauseofdependenciesoflanguagefeaturesonlibrarysupport,eveniftheclassfilesproducedbytheJava5compilercouldbeloadedbyearlierJVMversions,executionwouldstillfailbecauseofclassloadingerrors.However,itshouldbepossibletosolvetheseproblemsbysuitablytransformingthebytecodebecausethesemissingclassesdonotcontainsubstantialnewfunctionality.
JSR14
DuringthedevelopmentoftheJavagenericsspecification(andotherlanguagefeaturesaddedinJava5),experimentalsupportwasaddedtothejavaccompilertoallowittoconsumeJava5languagefeaturesandgeneratebytecodethatcouldberunonaJava1.4JVM.Whilethesefeaturesarenotsupported(orevendocumented),theyareusedbyanumberofopensourceprojectstoallowdeveloperstocodeusingJava5languagefeaturesandproduceJARfilesthatcanbeusedonearlierJVMs.And,nowthatjavacisopensource,itispossiblethefeaturesmightbesupportedbyathirdparty.Toactivatethesefeatures,youcaninvokejavacwiththe-source1.5and-targetjsr14options.
TheJSR14targetmodeofjavaccausesthecompilertoemitJDK1.4-compatiblebytecodecorrespondingtoJava5languagefeatures:
∙Genericsandvarargs:
Thecastsinsertedbythecompilerinthepresenceofgenericshavenodependencyontheclasslibrary,andsotheycanexecuteequallywellonapre-5JVM.Similarly,thecodegeneratedbythecompilerinthepresenceofvariable-lengthargumentlistshasnodependencyontheclasslibrary.
∙for-eachloop:
Wheniteratingoveranarray,thecompilergeneratesaninductionvariableandthestandardarrayiterationidiom.WheniteratingoveraCollection,thecompilergeneratesthestandarditerator-basedidiom.Wheniteratingoveranon-CollectionIterable,thecompilerproducesanerror.
∙Autoboxing:
RatherthangeneratingcallstothevalueOf()methodinthewrapperclass,thecompilergeneratescallstotheconstructorinstead.
∙Stringconcatenation:
TheJSR14targetmodeofjavaccausesthecompilertogeneratecallstoStringBufferinsteadofStringBuilder.
∙Enumerations:
TheJSR14targetmodeofjavachasnospecialsupportforenumerations.CodethatattemptstouseenumerationswillfailwithaNoClassDefFoundErrorlookingforthejava.lang.Enumbaseclass.
UsingtheJSR14targetmodeallowsyoutowritecodethatusesgenerics,autoboxing,andthefor-eachloopinthe"easy"cases,whichmaysufficeformanyprojects.Itisconvenient,ifunsupported,andthecompilergeneratesmostlycompatiblebytecodeinasinglepass.
Retroweaver
TherearecertainJava5languagefeaturesnotsupportedbytheJSR14targetmode(suchasIterableandenumerations).Analternateapproach,takenbyopen-sourceprojectssuchasRetroweaverandRetrotranslator,istogeneratebytecodeusing-ta