Time to get Groovy

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:
Person.java

package com.cherouvim.blog;
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:
Person.groovy

package com.cherouvim.blog
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:
GroovyLoader

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

Now let’s test our concrete PersonGroovy class:
PersonTest.java

  Person p;
  public void setUp() {
    p = (Person)GroovyLoader.loadGroovyObject(
        "com/cherouvim/blog/Person.groovy");
  }

  /**
   * Test java method
   */
  public void testShouldStartSmoking() {
    assertFalse(p.shouldStartSmoking());
  }

  /**
   * Test groovy method
   */
  public void testIsAllowedToDriveCar() {
    p.setAge(14);
    assertFalse(p.isAllowedToDriveCar());
    p.setAge(27);
    assertTrue(p.isAllowedToDriveCar());
  }

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.

Leave a Reply

You must be logged in to post a comment.