Java Reference
In-Depth Information
If I saved this into a file called hello_world.groovy I could execute the script using the
groovy command, which would compile it and run it all in one process. To run it using
the java command, however, first I have to compile it with groovyc and then execute
the resulting bytecodes, making sure the groovy-all JAR is in the classpath. The two-step
process is shown. Note that the java command should be all on one line:
> groovyc hello_world.groovy
> java -cp
.:$GROOVY_HOME/embeddable/groovy-all-2.1.5.jar
hello_world
→ Hello, Groovy!
I needed the groovyc command in order to compile the script, but I was able to execute
it using plain old java (as long as the groovy-all JAR was in the execution classpath).
At the API level, to call a Groovy script from Java you have a few alternatives. I'll first
showthe “hardest” waypossible, usingthe JSR-223 API.The APIassociated with JSR 223
is designed to allow Java programs to invoke scripts written in other languages.
I'm calling this “ the hard way because it doesn't take advantage of anything provided by
Groovy other than the script itself. I'll use the layers of indirection provided by the Java
API, which separates the Groovy code from the Java code that invokes it. Later you'll start
mixing Java and Groovy by combining classes and methods, and you'll find that's much
easier. Still, it's worth seeing how to use the JSR, especially because, after all, it is the
standard. Also, even if it's technically the hard way, it's really not all that hard.
3.2.1. Using JSR223 scripting for the Java Platform API
Built into Java SE 6 and above, the API for JSR 223, Scripting for the Java Platform, is a
standard mechanism you can use to call scripts written in other languages. The advantage
to this approach is that it avoids introducing anything specific to Groovy into the calling
Java program. If you already have Groovy scripts and you just want to call them from in-
side Java, this is a good way to go.
JSR 223
The JSR allows you to call Groovy scripts using purely Java classes.
Search WWH ::




Custom Search