GroovyShell().parse passing parameters

前提是你 提交于 2020-06-28 03:00:26

问题


I have a groovy script that needs to parse a class from an external groovy script. I am not sure how to pass parameters. Here is what works:

Groovy script I am running is using this line to parse the external class from external.groovy:

new GroovyShell().parse(new File('External.groovy'))

Here is what external.groovy looks like:

class External {
    public external() {
        println "Hello"
    }
}

It works.

The problem I am having, I cant find a way to pass parameters to the external method. Here is what external.groovy should look like:

class External {
    public external(String name) {
        println name
    }
}

How do I add parameters to the running script:

new GroovyShell().parse(new File('external.groovy')) //need to include the 'Name' parameter to this

回答1:


  1. parse only parses your file and doesn't execute it
  2. you have to call run as well
  3. you need to instantiate your file AND you need to call your method and give it the parameter
  4. you need to give the parameter via an Binding object

Here is the class and the call

class External {
     public external(String name) {
        println name
    }
}
new External.external(somename)

and then

def bindings = new Binding()
bindings.setVariable("somename", "mrhaki")
def shell = new GroovyShell(bindings)
shell.parse(new File('external.groovy'))
shell.run()


来源:https://stackoverflow.com/questions/24154876/groovyshell-parse-passing-parameters

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