Groovy - Define variable where the variable name is passed by another variable

淺唱寂寞╮ 提交于 2021-02-08 11:23:23

问题


I want define a variable in groovy with where the variable name is passed by another variable.

Something like.

def runExtFunc(varName){
    def varName  // => def abc
    varName = load 'someFile.groovy'   // abc = load 'someFile.groovy'

    varName."$varName"() // -> abc.abc() (run function defined in File)
}

    [...]
runExtFunc('abc')  // -> abc.abc() (Function abc defined in File)
    [...]
runExtFunc('xyz')  // -> xyz.xyz() (Function xyz defined in File)
    [...]

Sadly def varName defines the variable varName and not abc. When I call runExtFunc twice an error occoures bacause varName is already defined.

I also tried

def runExtFunc(varName){
    def "${varName}"  // => def abc
       [...]
    "${varName}" =  load 'someFile.groovy'
       [...]
}

which doesn't work either.

Any suggestions?


回答1:


This is the wrong approach. Normally you would use List, Map or Set data structures, which allow you to save a collection and access specific elements in the collection.

List allows you to hold specific values (unique or non-unique). Set allows you to hold specific values (all unique). Map allows you to have Key, Value pairs (Key must be unique) .

Read more here groovy list, groovy map




回答2:


Try this (if I understand you correctly):

def dummyFunc(varName) {
  new GroovyShell(this.binding).evaluate("${varName}")
}

dummyFunc('abc')

abc = "Hello there"
println abc

Prints

Hello there


来源:https://stackoverflow.com/questions/37854495/groovy-define-variable-where-the-variable-name-is-passed-by-another-variable

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