Groovy and java

Dynamic scripting languages are terse. This makes for quick solutions and more maintainable code. In the past I have embedded scripting languages like TCL/TK in C/C++ based applications. Consultants can then add functionality to a product at a client site with much less effort than is required by the R&D staff. BUT the two languages sit apart and to provide C++ functions to TCL, well add it to the R&D guys job list.

Groovy makes the sometimes verbose Java more palatable. But more importantly, it is very easy to mix the two and in a far more advanced way than one could have ever done with TCL and C/C++.

Sometimes a simple example is all that one needs to get the idea. Here is that example.

Edit a simple java base class, something obvious like

$ cat JBase.java

public class JBase {
  public void doIt() {
    System.out.println("Java: JBase");
  }

  public static void main(String [] args) {
    JBase jbase = new JBase();
    jbase.doIt();
  }
}

Create your bytecode (JBase.class)

$ javac JBase.java

Edit a Groovy script to use the above

$ cat G_uses_J.groovy

JBase jbase = new JBase()
jbase.doIt()

And create your Groovy bytecode (G_uses_J.class)

$ groovyc G_uses_J.groovy

And finally run it

$ groovy G_uses_J
Java: JBase

Hey presto. I think you will get the idea, the two languages can be mixed up much more than a simple example will show, but let me spell it out though, “Mixing scripting with Java is dead easy, and if you use Java then you can already use Groovy!”

Give it a go, make your product more customizable at client sites!

ADDENDUM: Thank you Bob for this very important point. Call our groovy code directly from Java like so (note the groovy library). It is indeed all JVM bytecode compatible.

    java -classpath .;c:/Dev/groovy-1.5.7/embeddable/groovy-all-1.5.7.jar G_uses_J
Java: JBase

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s