精品文档504关于计算机专业JAVA语言类有关的外文文献翻译成品Nashorn的Java API中英文双语对照.docx
《精品文档504关于计算机专业JAVA语言类有关的外文文献翻译成品Nashorn的Java API中英文双语对照.docx》由会员分享,可在线阅读,更多相关《精品文档504关于计算机专业JAVA语言类有关的外文文献翻译成品Nashorn的Java API中英文双语对照.docx(21页珍藏版)》请在冰豆网上搜索。
精品文档504关于计算机专业JAVA语言类有关的外文文献翻译成品Nashorn的JavaAPI中英文双语对照
英文2646单词,14808字符(字符就是印刷符),中文3875汉字。
JavaAPIsforNashorn
Inthischapter,youwilllearn:
WhatJavaAPIsforNashornare
HowtoinstantiatetheNashornenginedirectly
HowtopassoptionstotheNashornengineinJavacodeandonthecommand-line
HowtoshareglobalsamongscriptcontextsinaNashornengine
Howtoadd,update,delete,andreadpropertiesofscriptobjectsinJavacode
HowtocreatescriptobjectsandinvoketheirmethodsinJavacode
HowtoinvokescriptfunctionsfromJavacode
HowtoconvertscriptdatestoJavadates
WhatAreJavaAPIsforNashorn?
ItisstraightforwardtouseJavaclassesinNashornscripts.SometimesyoumaywanttouseNashornobjectsinJavacode.YoumaypassNashornobjectstoJavacodeorJavacodemayevaluateaNashornscriptandretrievethereferenceofNashornobjects.WhenNashornobjectscrosstheboundary(script-to-Java),theyneedtoberepresentedasobjectsofaJavaclassandyoushouldbeabletousethemlikeanyotherJavaobjects.
IfyourapplicationusesonlyNashorn,totakefulladvantageoftheNashornengineyoumaywanttouseoptionsandextensionsavailableinNashorn.YouwillneedtoinstantiatetheNashornengineinJavacode,usingtheclassesthatarespecifictotheNashornengine,notusingtheclassesintheJavaScriptingAPI.TheJavaAPIsforNashornprovideJavaclassesandinterfacesthatletyoudealwiththeNashornscriptingengineandNashornobjectsdirectlyinJavacode.Figure12-1depictsaclassdiagramofthoseclassesandinterfacesthatyouaresupposedtouseintheclientcodewhenyouaredealingwiththeNashornengine.Theyareinthenjdk.nashorn.api.scriptingpackage.
NotethattheNashornscriptingengineinternallyusesalotofotherclassesinotherpackages.However,youarenotsupposedtousetheminyourapplicationdirectly,exceptforclassesfromthejdk.nashorn.api.scriptingpackage.Thewebpageathttps:
//wiki.openjdk.java.net/display/Nashorn/Nashorn+jsr223+engine+notescontainsthelinksforthedocumentationforthejdk.nashorn.api.scriptingpackage.
IwilldiscusssomeNashorn-specificJavaclassesandinterfacesindetailinsubsequentsections.Table12-1liststheclassesandinterfacesinthejdk.nashorn.api.scriptingpackagewiththeirdescriptions.
InstantiatingtheNashornEngine
Inpreviouschapters,youhavebeeninstantiatingtheNashornengineinJavacodeusingthestandardJavaScriptingAPI.TheNashornengineprovidesseveralcustomfeatures.Totakeadvantageofthosefeatures,youwillneedtoinstantiatetheNashornenginedirectly.First,youwillneedtocreateanobjectoftheNashornScriptEngineFactoryclass,andthencalloneoftheoverloadedversionsofthegetScriptEngine()methodtocreateaNashornengine:
Bydefault,theNashornenginefactorycreatesaNashornenginewiththe--dump-on-erroroptionenabled.IwillshowyouhowtosetotheroptionsfortheNashornengineinthenextexample.Becauseofthe--no-javaoption,youcannotuseanyJavaclassesinsidethescriptsexecutedbythisengine.The–strictoptionwillforcetheenginetoexecuteallscriptsinstrictmode.ThefollowingsnippetofcodecreatesaNashornengineusingaclassfilter,whichisaninstanceoftheClassFilterinterface,torestricttheusageofanyclassesfromthecom.jdojopackageanditssubpackages.NoticethattheClassFilterinterfacewasaddedinJDK8u40;itisnotavailableinJDK8.
ClassFilterisafunctionalinterface.ItsmethodispassedthefullyqualifiednameoftheJavaclassthattheNashornscriptistryingtouse.Ifthemethodreturnstrue,theclasscanbeusedinthescript;otherwise,theclasscannotbeusedinthescript.
ThefollowingisalistoftheoverloadedversionsofthegetScriptEngine()methodoftheNashornScriptEngineFactoryclass:
SharingtheEngineGlobals
Bydefault,theNashornenginemaintainstheglobalobjectsperscriptcontext.Inthisdiscussion,theterm“globals”meanstheglobalvariablesanddeclarationsstoredintheglobalscopeoftheNashornscript,whichyourefertobythisinthetop-levelscripts.Donotmixuptheglobalscopebindingsinthescriptcontextwiththeglobalsinthescript.Thescriptglobalsaresearchedfirstwhenyoureferenceanyvariablesorcreatevariablesinyourscript.Ifyoureferenceavariableinascriptthatisnotfoundinthescriptglobals,theenginewillsearchforitintheglobalscopebindingsofthescriptcontext.Forexample,thescriptobjectsObject,Math,String,andsoonarepartofthescriptglobals.ConsidertheprogramanditsoutputinListing12-1.
Theprogramperformsthefollowingsteps:
1.CreatesaNashornenginewithdefaultoptions.
2.Executesascriptusingtheeval()methodthatusesthedefaultscriptcontextoftheengine.Thescriptcreatesaglobalvariablenamedmsgthatisstoredinthescriptglobals.Youcanrefertothevariableusingitssimplenamemsgorthis.msgintheglobalscope.
3.Executesascriptusingtheeval()methodthatusesthedefaultscriptcontextoftheenginethatprintsthevalueofthemsgvariable.Thefirstlineintheoutputconfirmsthatthecorrectvalueofthemsgvariableisprinted.
4.Executesascriptusingtheeval()methodthatusesanewscriptcontext.Thescripttriestoprintthevalueoftheglobalvariablemsg.Thesecondlineintheoutput,byprintingundefined,confirmsthatthevariablenamedmsgdoesnotexistinthescriptglobals.
ThisisthedefaultbehavioroftheNashornengine.Itcreatesafreshcopyoftheglobalsperscriptcontext.Ifyouwanttousetheglobalsofthedefaultcontext(ifyouwanttoshareglobals),youcandosobycopyingtheenginescopeBindingsofthedefaultcontexttoyournewscriptcontext.Listing12-2usesthisapproachtosharethescriptglobalsbetweentwoscriptcontexts.
The–-global-per-engineoptionfortheNashornengineaccomplishesthesamethingsasinthepreviousexample.Itsharesthescriptglobalsamongallscriptcontexts.Listing12-3showshowtosetthisoptionfortheengine.Theoutputconfirmsthattheengineisusingonlyonecopyofglobalstoexecuteallscripts.
UsingScriptObjectsinJavaCode
WhenobjectsandvaluesfromNashorncrossthescript-JavaboundarytoenterJavacode,theyneedtoberepresentedasJavaobjectsandvalues.Table12-2liststhemappingofclassesbetweenscriptobjectsandtheircorrespondingJavaobjects.
Notethatyouarenotsupposedtousetheclassesandinterfacesinthejdk.nashorn.internalpackageanditssubpackages.Theyarelistedinthetableonlyforinformationalpurposes.Inthistable,themappingfortheNashornNumbertypeisshownasjava.lang.Numbertype.AlthoughNashorntriestopassjava.lang.Integerandjava.lang.
Doubleobjectsfornumericvaluewheneverpossible,itisnotreliabletodependonsuchspecializedJavatypes.Youshouldexpectajava.lang.NumberinstancewhenaNashornNumberispassedfromascripttoJavacode.Whenevernecessary,valuesofNumberandBooleantypesinNashornareconvertedtothecorrespondingJavaprimitivetypes,suchasint,double,boolean,andsoon.
InNashorn,ascriptobjectisrepresentedasaninstanceofthejdk.nashorn.internal.runtime.ScriptObjectclass.WhenthescriptobjectispassedtoJavacode,itiswrappedinaScriptObjectMirrorobject.BeforeJDK8u40,ifyoupassedascriptobjecttoaJavamethodthatdeclareditsparameterasjava.lang.Objecttype,aScriptObjectwaspassed,notaScriptObjectMirror.JDK8u40haschangedthisbehaviortopassascriptobjecttoJavacodeasaScriptObjectMirroreverytime.Ifyouhaddeclaredthemethod’sparameterasJSObjectorScriptObjectMirrorinJava,NashornalwayspassedthescriptobjecttoJavaasaScriptObjectMirror.
TheScriptObjectMirrorclassimplementstheJSObjectandBindingsinterfaces.Theclassaddsmoremethodstodealwithscriptobjects.YoucanstorethereferenceofascriptobjectinJavacodeinanyofthethreetypesofvariables:
JSObject,Bindings,orScriptObjectMirror.Whattypeyouusedependsonyourneeds.UsingtheScriptObjectMirrortypegivesyoumoreflexibilityandaccesstoallfeaturesofthescriptobject.Table12-3containsthelistofmethodsdeclaredintheJSObjectinterface.
IwillshowhowtousethesemethodsandsomemethodsoftheScriptObjectMirrorclassinthesubsequentsection.TheJSObjectinterfacecanbeimplementedbyanyJavaclass.Objectsofsuchaclasscanbeusedjustasiftheyarescriptobjectsandcanusethesyntaxobj.func(),obj[prop],deleteobj.prop,andsoontoworkwiththeirmethodsandpropertiesinscripts.
UsingPropertiesofScriptObjects
TheScriptObjectMirrorclassimplementsJSObjectandBindingsinterfaces.Youcanusemethodsofbothinterfacestoaccessproperties.YoucanusethegetMember()andgetSlot()methodsofJSObjecttoreadthenamedandindexedpropertiesofthescriptobject.Youcanusetheget()methodofBindingstogetthevalueofaproperty.YoucanusethesetMember()andsetSlot()methodsofJSObjecttoaddandupdateaproperty.Theput()methodofBindingsletsyoudothesame.
YoucanusethehasMember()andhasSlot()methodsofJSObjecttocheckwhetheranamedpropertyandanindexedpropertyexist.Atthesametime,youcanusethecontainsKey()methodoftheBindingsinterfacetocheckwhetherapropertyexists.YoucanthinkoftheJSObjectandBindingsinterfacesimplementedbytheScriptObjectMirrorclassprovidingtwoviewsofthesamescriptobject—theformerasasimpleobjectandthelatterasamap.
Listing12-4