Compiling user entered groovy script at run time

前端 未结 1 1884
长发绾君心
长发绾君心 2021-01-17 03:06

Have a scenario as below where I need to validate the groovy script for correctness.

class CostCalculator{

String name
String groovyScript

static constrain         


        
相关标签:
1条回答
  • 2021-01-17 03:26

    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.

    0 讨论(0)
提交回复
热议问题