简体   繁体   English

如何将groovy dsl脚本从一个groovy文件添加到另一个文件

[英]how to include groovy dsl script from one groovy file to another

I have created a custom dsl command chain using methods in a groovy scripts . 我已经使用groovy脚本中的方法创建了一个自定义dsl命令链。 I have a problem in accessing this command chain from another groovy file . 我从另一个常规文件访问此命令链时遇到问题。 Is there a way to achieve the functionality ? 有没有办法实现功能?

I have tried using "evaluate" which is able to load the groovy file , but it is not able to execute the command chain. 我尝试使用“ evaluate”能够加载groovy文件,但无法执行命令链。 I have tried using Groovy shell class , but was not able to call the methods. 我尝试使用Groovy shell类,但是无法调用方法。

show = { 
        def cube_root= it
}

cube_root = { Math.cbrt(it) }

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

please show the cube_root of 1000

Here I have a CubeRoot.groovy in which executing "please show the cube_root of 1000" produces the result as 10 在这里,我有一个CubeRoot.groovy,其中执行“请显示1000的cube_root”将结果显示为10

I have another groovy file called "Main.groovy" . 我还有一个名为“ Main.groovy”的常规文件。 Is there a way to execute the above command chain directly in Main.groovy as "please show the cube_root of 1000" and get the desired output ? 有没有一种方法可以直接在Main.groovy中执行上述命令链,如“请显示1000的cube_root”并获得所需的输出?

Main.groovy Main.groovy

please show the cube_root of 1000

there is no include operation in groovy/java 在groovy / java中没有include操作

and you could use GroovyShell 您可以使用GroovyShell

if you could represent your "dsl" as closures then for example this should work: 如果您可以将“ dsl”表示为闭包,那么这应该可以工作:

//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 文件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 文件Main.groovy

Lang1.init(this)

please show the cube_root of 1000

and run from command line: groovy Main.groovy 并从命令行运行: groovy Main.groovy

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM