Stuff about software development, agile and testing

Tuesday, August 12, 2008

Using Groovy Script

Groovy Script

Groovy Scripts are different from Groovy classes, in Groovy Scripts you can directly write code without declaring methods or classes (just like your bash or perl scripts). We can use Groovy Scripts from Groovy classes, Java classes or using "java" to run them.

From Java Classes

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("groovy");
System.out.println("Calling script from Java");
try
{
engine.eval(new FileReader("MyGroovyScript.groovy"));
}
catch(ScriptException ex)
{
System.out.println(ex);
}

Note: Make sure your groovy-engine.jar file is in your classpath

From Other Groovy Scripts

def shell = new GroovyShell()
shell.evaluate(new File('MyGroovyScript.groovy'))

From Command line

We can compile our Groovy Scripts using groovyc compiler and when you do that it will create a single ".class" file based on name of the script with auto generated main(String[] args) method. Once you have a main method we can clearly run using java command, no tricks there. The auto generated main method creates an instance of the class which extends groovy.lang.Script and invokes run method on it (We will come back to this)

From Groovy Classes

def runSomeScript() {

...

run(MyGroovyScript)

...

}

What the heck is this? Are we missing something?

No we are not. In Groovy (like Ruby) class names are constant and in Groovy this constant points to java.lang.Class class of the class created by the groovyc compiler. So now if I have a method like following I would be able to run the script

def run(Class scriptClass) {//You don't have to specify type, I did for clarity

Script script = InvokerHelper.createScript(scriptClass, new Binding()) //Binding is a way to share variables and context info with Script

script.run()

}

Labels