Tải bản đầy đủ - 0 (trang)
Chapter 11. Scripting, Compiling, and Annotation Processing

Chapter 11. Scripting, Compiling, and Annotation Processing

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

Enablingcustomizationbyprogramusers.

Ontheotherhand,mostscriptinglanguageslackfeaturesthat

arebeneficialforprogrammingcomplexapplications,suchas

strongtyping,encapsulation,andmodularity.

Itisthereforetemptingtocombinetheadvantagesofscripting

andtraditionallanguages.ThescriptingAPIletsyoudojustthat

fortheJavaplatform.Itenablesyoutoinvokescriptswrittenin

JavaScript,Groovy,Ruby,andevenexoticlanguagessuchas

SchemeandHaskell,fromaJavaprogram.(Theotherdirection,

accessingJavafromthescriptinglanguage,istheresponsibility

ofthescriptinglanguageprovider.Mostscriptinglanguagesthat

runontheJavavirtualmachinehavethiscapability.)

Inthefollowingsections,weshowyouhowtoselectanengine

foraparticularlanguage,howtoexecutescripts,andhowto

takeadvantageofadvancedfeaturesthatsomescripting

enginesoffer.



GettingaScriptingEngine

Ascriptingengineisalibrarythatcanexecutescriptsina

particularlanguage.Whenthevirtualmachinestarts,it

discoverstheavailablescriptingengines.Toenumeratethem,

constructaScriptEngineManagerandinvokethe

getEngineFactoriesmethod.Youcanaskeachenginefactory

forthesupportedenginenames,MIMEtypes,andfile

extensions.Table11-1showstypicalvalues.

Table11-1.PropertiesofScriptingEngineFactories

Engine

Names

MIMEtypes

Extensions

Rhino

js,rhino,

(includedin JavaScript,

JavaSE6) javascript,

ECMAScript,

ecmascript



application/javascript, js

application/ecmascript,

text/javascript,

text/ecmascript]



Groovy



None



groovy



groovy



SISC

Scheme



scheme,sisc



None



scc,sce,

scm,shp



Usually,youknowwhichengineyouneed,andyoucansimply

requestitbyname,MIMEtype,orextension.Forexample,

ScriptEngineengine=manager.getEngineByName("JavaScript");



JavaSE6includesaversionofRhino,aJavaScriptinterpreter

developedbytheMozillafoundation.Youcanaddadditional

languagesbyprovidingthenecessaryJARfilesontheclass

path.YouwillgenerallyneedtwosetsofJARfiles.Thescripting

languageitselfisimplementedbyasingleJARfileorasetof

JARs.TheenginethatadaptsthelanguagetothescriptingAPI

usuallyrequiresanadditionalJAR.Thesite

http://scripting.dev.java.netprovidesenginesforawiderange

ofscriptinglanguages.Forexample,toaddsupportforGroovy,

theclasspathshouldcontaingroovy/lib/*(from

http://groovy.codehaus.org)andgroovy-engine.jar(from

http://scripting.dev.java.net).



javax.script.ScriptEngineManager6

List

getEngineFactories()

getsalistofalldiscoveredenginefactories.

ScriptEnginegetEngineByName(String

name)

ScriptEngine

getEngineByExtension(Stringextension)

ScriptEnginegetEngineByMimeType(String

mimeType)

getsthescriptenginewiththegivenname,

scriptfileextension,orMIMEtype.



javax.script.ScriptEngineFactory6

ListgetNames()

ListgetExtensions()

ListgetMimeTypes()

getsthenames,scriptfileextensions,and

MIMEtypesunderwhichthisfactoryisknown.



ScriptEvaluationandBindings

Onceyouhaveanengine,youcancallascriptsimplyby

invoking

Objectresult=engine.eval(scriptString);



Ifthescriptisstoredinafile,thenopenaReaderandcall

Objectresult=engine.eval(reader);



Youcaninvokemultiplescriptsonthesameengine.Ifone

scriptdefinesvariables,functions,orclasses,mostscripting

enginesretainthedefinitionsforlateruse.Forexample,

engine.eval("n=1728");

Objectresult=engine.eval("n+1");



willreturn1729.



Note

Tofindoutwhetheritissafetoconcurrentlyexecute

scriptsinmultiplethreads,call

Objectparam=factory.getParameter("THREADING");



Thereturnedvalueisoneofthefollowing:

null:Concurrentexecutionisnotsafe

"MULTITHREADED":Concurrentexecutionissafe.

Effectsfromonethreadmightbevisiblefromanother

thread.

"THREAD-ISOLATED":Inadditionto

"MULTITHREADED",differentvariablebindingsare

maintainedforeachthread.

"STATELESS":Inadditionto"THREAD-ISOLATED",

scriptsdonotaltervariablebindings.



Youoftenwanttoaddvariablebindingstotheengine.Abinding

consistsofanameandanassociatedJavaobject.Forexample,

considerthesestatements:

engine.put(k,1728);

Objectresult=engine.eval("k+1");



Thescriptcodereadsthedefinitionofkfromthebindingsinthe

"enginescope."Thisisparticularlyimportantbecausemost



scriptinglanguagescanaccessJavaobjects,oftenwithasyntax

thatissimplerthantheJavasyntax.Forexample,

engine.put(b,newJButton());

engine.eval("f.text='Ok'");



Conversely,youcanretrievevariablesthatwereboundby

scriptingstatements:

engine.eval("n=1728");

Objectresult=engine.get("n");



Inadditiontotheenginescope,thereisalsoaglobalscope.

AnybindingsthatyouaddtotheScriptEngineManagerare

visibletoallengines.

Insteadofaddingbindingstotheengineorglobalscope,you

cancollecttheminanobjectoftypeBindingsandpassthem

totheevalmethod:

Bindingsscope=engine.createBindings();

scope.put(b,newJButton());

engine.eval(scriptString,scope);



Thisisusefulifasetofbindingsshouldnotpersistforfuture

callstotheevalmethod.

Note

Youmightwanttohavescopesotherthan

theengineandglobalscopes.Forexample,

awebcontainermightneedrequestand

sessionscopes.However,thenyouareon



yourown.Youneedtoimplementaclass

thatimplementstheScriptContext

interface,managingacollectionofscopes.

Eachscopeisidentifiedbyaninteger

number,andscopeswithlowernumbers

shouldbesearchedfirst.(Thestandard

libraryprovidesaSimpleScriptContext

class,butitonlyholdsglobalandengine

scopes.)



javax.script.ScriptEngine6

Objecteval(Stringscript)

Objecteval(Readerreader)

Objecteval(Stringscript,Bindings

bindings)

Objecteval(Readerreader,Bindings

bindings)

evaluatesthescriptgivenbythestringor

reader,subjecttothegivenbindings.

Objectget(Stringkey)

voidput(Stringkey,Objectvalue)

getsorputsabindingintheenginescope.

BindingscreateBindings()

createsanemptyBindingsobjectsuitablefor

thisengine.



javax.script.ScriptEngineManager6

Objectget(Stringkey)

voidput(Stringkey,Objectvalue)

getsorputsabindingintheglobalscope.



javax.script.Bindings6

Objectget(Stringkey)

voidput(Stringkey,Objectvalue)

getsorputsabindingintothescope

representedbythisBindingsobject.



RedirectingInputandOutput

Youcanredirectthestandardinputandoutputofascriptby

callingthesetReaderandsetWritermethodofthescript

context.Forexample,

StringWriterwriter=newStringWriter();

engine.getContext().setWriter(newPrintWriter(writer,true));



AnyoutputwrittenwiththeJavaScriptprintorprintln

functionsissenttowriter.

Caution

YoucanpassanyWritertothesetWriter

method,buttheRhinoenginethrowsan

exceptionifitisnotaPrintWriter.



ThesetReaderandsetWritermethodsonlyaffectthescripting



engine'sstandardinputandoutputsources.Forexample,ifyou

executetheJavaScriptcode

println("Hello");

java.lang.System.out.println("World");



onlythefirstoutputisredirected.

TheRhinoenginedoesnothavethenotionofastandardinput

source.CallingsetReaderhasnoeffect.



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

Chapter 11. Scripting, Compiling, and Annotation Processing

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

×