如何将groovy dsl脚本从一个groovy文件包含到另一个groovy文件中

问题描述 投票:1回答:1

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

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

这里我有一个Cube Root.groovy,其中执行“请显示1000的立方根”会产生10的结果

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

Main.groovy

please show the cube_root of 1000

java groovy dsl
1个回答
0
投票

在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

© www.soinside.com 2019 - 2024. All rights reserved.