Groovy-定义变量,其中变量名由另一个变量传递 [英] Groovy - Define variable where the variable name is passed by another variable

查看:109
本文介绍了Groovy-定义变量,其中变量名由另一个变量传递的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在groovy中定义一个变量,其中变量名由另一个变量传递.

类似.

  def runExtFunc(varName){def varName//=>def abcvarName =加载'someFile.groovy'//abc =加载'someFile.groovy'varName."$ varName"()//->abc.abc()(运行在文件中定义的功能)}[...]runExtFunc('abc')//->abc.abc()(在文件中定义的功能abc)[...]runExtFunc('xyz')//->xyz.xyz()(在文件中定义的功能xyz)[...] 

可悲的是,def varName定义变量varName而不是abc.当我两次调用runExtFunc时,由于已经定义了varName,所以会出现错误.

我也尝试过

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

也不起作用.

有什么建议吗?

解决方案

这是错误的方法.通常,您将使用列表地图设置数据结构,这些数据结构可用于保存集合并访问集合中的特定元素.

列表允许您保存特定的值(唯一或不唯一).设置可让您保留特定值(所有值都是唯一的).地图允许您具有键,值对(键必须是唯一的).

在此处阅读更多常规列表常规地图

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?

解决方案

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

这篇关于Groovy-定义变量,其中变量名由另一个变量传递的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆