how to include groovy dsl script from one groovy file to another

南笙酒味 提交于 2019-12-06 05:39:04

there is no include operation in groovy/java

and you could use GroovyShell

if you could represent your "dsl" as closures then for example this should work:

//assume you could load the lang definition and expression from files  
def cfg = new ConfigSlurper().parse( '''
    show = { 
            def cube_root= it
    }

    cube_root = { Math.cbrt(it) }

    please = {action->
        [the: { what ->
            [of: { n ->
                def cube_root=action(what(n))
                    println cube_root;
            }]
        }]
    }  
''' )

new GroovyShell(cfg as Binding).evaluate(''' please show the cube_root of 1000 ''')

another way - use class loader

file Lang1.groovy

class Lang1{
    static void init(Script s){
        //let init script passed as parameter with variables 
        s.show = { 
           def cube_root= it
        }
        s.cube_root = { Math.cbrt(it) }

        s.please = {action->
            [the: { what ->
                [of: { n ->
                    def cube_root=action(what(n))
                        println cube_root;
                }]
            }]
        }  
    }
}

file Main.groovy

Lang1.init(this)

please show the cube_root of 1000

and run from command line: groovy Main.groovy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!