【问题标题】:how to include groovy dsl script from one groovy file to another如何将 groovy dsl 脚本从一个 groovy 文件包含到另一个文件中
【发布时间】:2019-04-05 17:36:54
【问题描述】:

我使用 groovy 脚本中的方法创建了一个自定义 dsl 命令链。我从另一个 groovy 文件访问此命令链时遇到问题。有没有办法实现这个功能?

我曾尝试使用能够加载 groovy 文件的“评估”,但它无法执行命令链。我曾尝试使用 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

这里我有一个 CubeRoot.groovy,其中执行“请显示 1000 的 cube_root”产生的结果为 10

我有另一个名为 "Main.groovy" 的 groovy 文件。有没有办法直接在 Main.groovy 中执行上述命令链为“请显示 1000 的 cube_root”并获得所需的输出?

Main.groovy

please show the cube_root of 1000

【问题讨论】:

    标签: java groovy dsl


    【解决方案1】:

    groovy/java中没有include操作

    你可以使用 GroovyShell

    如果您可以将“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 ''')
    

    另一种方式——使用类加载器

    文件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;
                    }]
                }]
            }  
        }
    }
    

    文件Main.groovy

    Lang1.init(this)
    
    please show the cube_root of 1000
    

    并从命令行运行:groovy Main.groovy

    【讨论】:

    • 感谢您的回答。有什么方法可以将脚本加载为仅提供文件路径并绑定它而不是在 Main.groovy 中加载完整的脚本?
    • def cfg = new ConfigSlurper().parse( new File(path_to_config).toURI().toURL() )
    • 但是有很多变种。也许我只是不明白你想要什么..
    • 我想做的是,我在各种 groovy 文件中有各种类似于“请显示 1000 的 cube_root”的 groovy 语句。我想将所有这些 groovy 文件导入一个 groovy 并构建一个使用这些语句的新语句。有可能吗?
    • 我在答案中添加了另一个案例
    猜你喜欢
    • 2012-02-26
    • 1970-01-01
    • 2012-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-16
    • 1970-01-01
    • 2011-11-24
    相关资源
    最近更新 更多