Java Reference
In-Depth Information
becomes, what does Groovy bring to Java? How can you simplify your development tasks
by adding Groovy to Java systems? I'll address that question in the rest of the chapter (and,
indeed, in the rest of the topic). Let's start, though, with the scripting story. How do you
combine Java and Groovy in the same system when Groovy consists of scripts rather than
classes, and you want to isolate any Java integration code?
3.2. Executing Groovy scripts from Java
The assumption in the first couple of sections of this chapter is that you've written or ac-
quired some Groovy scripts and wish to use them in your Java system in a way that's min-
imally invasive. Perhaps you're using the scripts to implement business logic in Groovy
because it changes so frequently (a technique referred to as Liquid Heart by Dierk Koenig,
lead author of Groovy in Action [Manning, 2007]). Perhaps you're replacing Perl scripts
with Groovy because anything you can do in Perl you can do in Groovy, with the added bo-
nus that you can integrate with existing Java systems. Perhaps you're following one of the
original intents of the JSR, which is to use a scripting language to generate user interfaces
while letting Java handle the back-end functionality. In any case, I want to demonstrate
how to invoke those scripts from a Java system as easily as possible.
One of the interesting features of Groovy is that, unlike in Java, you don't have to put all
Groovy code into a class. You can just put all your Groovy code into a file called practic-
ally anything you like, as long as the file extension is .groovy, and then you can execute the
scripts with the groovy command. One possible sweet spot for Groovy is to write short,
simple programs without the clutter of creating a class with a main method in it, and here
I'll show how to incorporate scripts like that into a Java application.
In keeping with the standard I'll start with a technique based on JSR 223, Scripting for the
Java Platform, which allows you to invoke Groovy purely from Java library calls. Then I'll
show that if you use a couple of classes from the Groovy API you can simplify the integra-
tion. Finally, I'll show that if you can change from scripts to classes for your Groovy code,
nearly all the complexity can be eliminated.
Incidentally, assuming any Groovy scripts are compiled, at runtime treat the combined ap-
plicationasthoughit'sallJava.AlltheintegrationstrategiesIplantodiscussinthischapter
involve deciding where and how to use Groovy to make your life easier. Once you have
Search WWH ::




Custom Search