Java Reference
In-Depth Information
Listing 3.5. Using
GroovyShell
and
Binding
to invoke the Google geocoder
Passing parameters into the script is easy enough using the
setVariable
method on the
Binding
. The binding is then used as an argument to the
GroovyShell
constructor.
The script is run from Java using the
evaluate
method as usual, and the results are ex-
tracted by getting the output variables from the shell. Using a
GroovyShell
and
Bind-
ing
is illustrated in
figure 3.5
.
Figure 3.5. Java code sets variables in the
Binding
, which is used in the
GroovyShell
to execute Groovy code.
The results are returned via the
getVariable
method in the
Binding
.
There's more to the
GroovyShell
than I'm presenting here. I can use the
parse
meth-
od, rather than
evaluate
, to parse the script and retrieve a reference to the generated
Script
object. That way I can set the binding variables and rerun the script without hav-
ing to recompile every time.
GroovyShell
also works with a hierarchy of classloaders