Generally speaking, there are two approaches for integrating Groovy with Java:
- Make the Java code compile and execute Groovy code at runtime
- Compile and package Groovy code as part of your build, just like you do for Java code
Use 1. if you need a "scripting" solution and the Groovy code to be executed is only known at runtime. For example, the code could be loaded from a database, or entered in a GUI screen. If you simply want to make your life easier by writing some parts of your application in Groovy, go with 2. Two typical examples where this can quickly pay off are XML parsing and testing (of course there are many more).
Assuming you are more interested in 2., you can either compile Groovy and Java separately or together. If you compile them separately, static references can only go in one direction, just as if you had two Java modules. If you compile them together, you can mix Groovy and Java code arbitrarily, as if it was all Java code in the same module.
Compiling Java and Groovy code together is made possible by a Groovy compiler feature called joint compilation. Unfortunately, GMaven has serious problems with joint compilation, and there is no sign that this will change any time soon. For smaller projects you might get away with it, but for larger projects it will bite you (I've been there). There are solutions, but they don't come for free. If you are open to (G)Maven alternatives, consider switching to Gradle, which has much better Groovy support. (Disclaimer: I'm one of the developers of Gradle.)
If you decide to stick to GMaven, make sure to get its configuration right. Almost every project I see fails at this step, often without realizing it. The GMaven documentation is outdated, but the Groovy mailing list contains several posts on the topic. You can also copy the configuration from Spock (one of my own projects).
To enable GMaven joint compilation, add the generateStubs
goal. As long as your project compiles without this goal, leave it out. There is also a generateTestStubs
goal, but it is rarely needed.
This is the short story. For the long story, check out the upcoming Manning book Making Java Groovy. (I'm not affiliated with the author.)