Executing Groovy scripts at runtime

25 / Sep / 2012 by Divya Setia 0 comments

A very useful Groovy class GroovyScriptEngine can be used to execute Groovy scripts at runtime.

For understanding purpose, lets start with an example. We have a script named as Area.groovy that calculates the area of circle.

[java]

// Area.groovy

Float r = "${radius}".toFloat() //radius will be passed as an argument to this script.

return "Area of the circle : " + Math.PI*r*r;

[/java]

Now if we want to execute the Area.groovy script at runtime, then the solution is to use GroovyScriptEngine class. For using GroovyScriptEngine class, there is need to pass the directory path to tell where the groovy script is saved. e.g.

[java]
GroovyScriptEngine gse = new GroovyScriptEngine(<Directory_Path>);
[/java]

If there is need to pass any argument in the script, then we can use Binding class to bind the argument with the script.

e.g.

[java]
import groovy.lang.Binding;
import groovy.util.GroovyScriptEngine;

GroovyScriptEngine gse = new GroovyScriptEngine("/home/divya/Desktop");

Binding binding = new Binding();

binding.setVariable("radius", 5); // Argument to be passed is "radius" with value 5

String areaOfCircle = gse.run("Area.groovy", binding);

println areaOfCircle

// Output: Area of the circle : 78.53981633974483
[/java]

The run method is used to execute the script.

Hope it would help!!

Divya Setia
divya@intelligrape.com
https://twitter.com/divs157

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *