Performance Zone is brought to you in partnership with:

Hi all, my name is Hubert A. Klein Ikkink. Not a very common name, right? To make things easier I just picked the first letters of my firstname and surname and came up with haki. So there you have it, now I am also known as Mr. Haki or mrhaki for short. You can read more blog postings at www.mrhaki.com. I am a passionate Groovy and Java developer based in Tilburg, The Netherlands. My goal is to write clean, elegant, user-centered and high quality software. You can find me on Google+ and Twitter. Hubert is a DZone MVB and is not an employee of DZone and has posted 167 posts at DZone. You can read more from them at their website. View Full User Profile

Groovy Goodness: Set Script Class with BaseScript Annotation

11.22.2013
| 7298 views |
  • submit to reddit

Groovy is of course great for writing DSLs. We can write our own Script class to implement a DSL that can be used when we evaluate a script. We can set the custom Script class via CompilerConfiguration. Since Groovy 2.2 we can use a new AST transformation @BaseScript. We must use this annotation in the script and set it on the custom script class. The name of the variable is not important, but the type must by the custom script class.

In the following DSL script we use the @BaseScript instead of the CompilerConfiguration as shown in previous blog post.

// Simple Car class to save state and distance.
class Car {
    String state
    Long distance = 0
}

// Custom Script with methods that change the Car's state.
// The Car object is passed via the binding.
abstract class CarScript extends Script {
    def start() {
        this.binding.car.state = 'started'
    }

    def stop() {
        this.binding.car.state = 'stopped'
    }

    def drive(distance) {
        this.binding.car.distance += distance
    }
}


// Define Car object here, so we can use it in assertions later on.
def car = new Car()
// Add to script binding (CarScript references this.binding.car).
def binding = new Binding(car: car)

// Configure the GroovyShell.
def shell = new GroovyShell(this.class.classLoader, binding)

// Simple DSL to start, drive and stop the car.
// The methods are defined in the CarScript class.
def carDsl = '''
start()
drive 20
stop()
'''


// Run DSL script.
shell.evaluate """
// Use BaseScript annotation to set script
// for evaluating the DSL.
@groovy.transform.BaseScript CarScript carScript

$carDsl
"""

// Checks to see that Car object has changed.
assert car.distance == 20
assert car.state == 'stopped'

Code written with Groovy 2.2.



Published at DZone with permission of Hubert Klein Ikkink, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)