Download NetBeans!

20071017 Wednesday October 17, 2007

Compiling and Running Groovy from Java in NetBeans IDE

Something I learned today at the Grails eXchange here in London. Without any plugins at all, you can already call Groovy scripts from Java code in NetBeans IDE, as outlined below.

  1. Start by creating a small script called "HelloWorld.groovy", using the "Empty File" template to create the file, with this content:
    package demojavaapplication
    class HelloWorld {
       static void main(args) {
             println "Hello from Groovy!"
       }
    }

    Now, we will set the project up so that the above will be called from a Java class in our application.

  2. First, here's an Ant script, added to my build.xml, that runs the Groovy compiler:
    <taskdef name="groovyc" 
             classpath="lib/groovy-all-1.0.jar" 
             classname="org.codehaus.groovy.ant.Groovyc"/>
    
    <target name="-pre-compile">
        <groovyc srcdir="${src.dir}" destdir="groovy">
            <classpath path="lib/groovy-all-1.0.jar"/>
        </groovyc>
    </target>

  3. Now, to use the above Ant script, do the following:

    • Right-click the Libraries node and add groovy-all-1.0.jar from the embeddable folder in the Groovy distribution. Now create a folder called "lib", in the Files window, and put the JAR there.

    • In the Files window, create a folder called groovy and add that folder to the Libraries node, which puts it on the classpath.

    You now have set "groovy" as your destination directory for the Groovy compiler. You have added the JAR that provides the Groovy compiler. You have added the "groovy" folder to the compile time classpath, so its content is compiled, prior to compilation of the Java classes.

  4. When you build your application, you should now see this, while taking note of the fact that your Groovy script is now a Java class:

  5. Since your Groovy script is now a Java class, and the folder that contains it is on the compile time classpath, you can call it from a Java source file:

    public class Main {
        public static void main(String[] args) {
            HelloWorld hello = new HelloWorld();
            hello.main(args);
        }
    }

    Plus, you have code completion from the Groovy script available to your Java class.

  6. Run the application and you have "Hello from Groovy!" in the Output window.

Oct 17 2007, 08:42:43 AM PDT Permalink