Have a scenario as below where I need to validate the groovy script for correctness.
class CostCalculator{
String name
String groovyScript
static constrain
I would recommend to put your groovy script in a class.
In the example you have method addCost(), so I would say just wrap this method in a class. ex:
String gScript = """
class CostCalculatorScript{
void addCost(int x, int y,String itemName){
double cost = x*y + originalCost
Item item = SoldItem.findByItemName(itemName)
item.price += cost
}
}
"""
Now load and parse this script using GroovyClassLoader.
ClassLoader gcl = new GroovyClassLoader()
Class clazz = gcl.parseClass(gScript)
Verify that the loaded class have the same name as you have specified in your script.
assert clazz.simpleName == 'CostCalculatorScript'
Now the kind of solution you want does seem like static compilation. You can add the @groovy.transform.CompileStatic annotation to your class. But with this annotation the problem is that you can't use the dynamic finders of grails or the def keyword.
But if you still want that functionality then you should use @grails.compiler.GrailsCompileStatic annotation which is available in Grails 2.4.