Over a million developers have joined DZone.

Groovy Goodness: BaseScript with Abstract Run Script Method

DZone's Guide to

Groovy Goodness: BaseScript with Abstract Run Script Method

· Java Zone
Free Resource

Learn how to troubleshoot and diagnose some of the most common performance issues in Java today. Brought to you in partnership with AppDynamics.

In a previous blog post we have seen how we can use a BaseScript AST transformation to set a base script class for running scripts. Since Groovy 2.3 we can apply the @BaseScript annotation on package and import statements. Also we can implement a run method in our Script class in which we call an abstract method. The abstract method will actually run the script, so we can execute code before and after the script code runs by implementing logic in the run method.

In the following sample we create a Script class CustomScript. We implement the run method and add the abstract method runCode:

// File: CustomScript.groovy
package com.mrhaki.groovy.blog

abstract class CustomScript extends Script {

    def run() {
        try {

            // Run actually script code.
            final result = runCode()

            println "Script says $result"
        } finally {
            println 'Script ended'

    private void before() {
        println 'Script starts'

    // Abstract method as placeholder for
    // the actual script code to run.
    abstract def runCode()

Next we create a Groovy script where we use our new CustomScript class.

// File: Sample.groovy
// Since Groovy 2.3 we can apply the
// @BaseScript annotation on package
// and import statement.
package com.mrhaki.groovy.blog

// Script code:
final String value = 'Groovy rules'
assert value.size() == 12

// Return value

When we run our script we see the following output:

Before script runs
Script says Groovy rules
Script ended

Code written with Groovy 2.3.

Understand the needs and benefits around implementing the right monitoring solution for a growing containerized market. Brought to you in partnership with AppDynamics.


Published at DZone with permission of Hubert Klein Ikkink, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.


Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.


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

{{ parent.tldr }}

{{ parent.urlSource.name }}