Over a million developers have joined DZone.
Platinum Partner

Groovy Goodness: Set Script Class with BaseScript Annotation

· Java Zone

The Java Zone is brought to you in partnership with ZeroTurnaround. Check out this 8-step guide to see how you can increase your productivity by skipping slow application redeploys and by implementing application profiling, as you code!

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.



The Java Zone is brought to you in partnership with ZeroTurnaround. Discover how you can skip the build and redeploy process by using JRebel by ZeroTurnaround.

Topics:

Published at DZone with permission of Hubert Klein Ikkink , DZone MVB .

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}