Archive for the ‘groovy’ Category

Time to get Groovy

Friday, March 2nd, 2007

Groovy is a dynamic language for Java. It allows you to do all funky stuff that you can do in dynamic languages, but still be able to write Java and execute inside the JVM.

Let’s get busy and write a simple Person Java class, in Java:

public abstract class Person {
  private int age;

  public Person() {

  public void setAge(int age) {
    this.age = age;

  public int getAge() {
    return this.age;

   * Determines whether this person should
   * start smoking.
   * Always returns false!
  public boolean shouldStartSmoking() {
    return false;

   * Determines whether this person is allowed
   * to drive a car.
   * To be implemented on subclass.
  public abstract boolean isAllowedToDriveCar();


This is an abstract class; it could have also been an interface. We want to add more behaviour now with Groovy code, so we are going to extend it and define the isAllowedToDriveCar method:

public class PersonGroovy extends Person {
  public boolean isAllowedToDriveCar() {
    return this.getAge()>18

In order to make this groovy script available to our Java program, we need to load it via the GroovyClassLoader. I define a helper method so I can easily get instances of Groovy classes:

public static final Object loadGroovyObject(String groovyScriptLocation) {
  GroovyClassLoader gc = new GroovyClassLoader();
  Class groovyClass = gc.parseClass(
  Object groovyObject = null;
  try {
    groovyObject = groovyClass.newInstance();
  } catch (Exception ex) {
    // log exception
  return groovyObject;

Now let’s test our concrete PersonGroovy class:

  Person p;
  public void setUp() {
    p = (Person)GroovyLoader.loadGroovyObject(

   * Test java method
  public void testShouldStartSmoking() {

   * Test groovy method
  public void testIsAllowedToDriveCar() {

This test gets an instance of the PersonGroovy class, casts it to the known type of Person and we are ready to go. The isAllowedToDriveCar method is available because we defined it in the abstract superclass. The tests pass.

Note that the way I’ve presented parses the groovy file every time we call loadGroovyObject which is slow. You can cache the class.