如何在Groovy中将字符串和变量连接成一个变量 3.1。普通标识符 3.2。带引号的标识符

我需要将字符串和变量串联到groovy中的布尔变量中, 情况是这样的:

我有一个循环,如果存在模式,我会寻找一个模式,我得到一个名为 cname 的变量,该变量具有一定的值。

现在,我想使用此值创建一个新的布尔参数,该布尔参数在布尔参数名称中包含 cname 参数的值。

这是我尝试过的:

boolean "trigger-${cname}" = true
boolean "trigger-"+${cname} = true

但是它似乎不适用于布尔值。 我希望能够有N个参数(多达 cname 次),其值为true。 例如,如果 cname 是(app,test,rest,.. N),则下面列出的所有布尔参数将为 true

trigger-app
trigger-test
trigger-rest
trigger-N
starfoucs 回答:如何在Groovy中将字符串和变量连接成一个变量 3.1。普通标识符 3.2。带引号的标识符

您不能使用带引号的标识符来定义标准变量。这是Groovy语法文档中的部分,对其进行了详细说明:

  

3。标识符

     

3.1。普通标识符

     

标识符以字母,美元或下划线开头。他们不能以数字开头。

     

字母可以在以下范围内:

     
      
  • 从“ a”到“ z”(小写的ascii字母)

  •   
  • 从“ A”到“ Z”(大写字母)

  •   
  • '\ u00C0'到'\ u00D6'

  •   
  • '\ u00D8'到'\ u00F6'

  •   
  • '\ u00F8'到'\ u00FF'

  •   
  • '\ u0100'到'\ uFFFE'

  •   
     

随后的字符可以包含字母和数字。

     

以下是有效标识符(此处为变量名)的一些示例:

def name
def item3
def with_underscore
def $dollarStart
     

但是以下标识符无效:

def 3tier
def a+b
def a#b
     

在点后加上所有关键字也是有效的标识符:

foo.as
foo.assert
foo.break
foo.case
foo.catch
     
     

来源:https://groovy-lang.org/syntax.html#_normal_identifiers

但是,当您定义Map时,可以使用带引号的标识符来访问其键值。

  

3.2。带引号的标识符

     

带引号的标识符出现在点表达式的点后。例如,person.name表达式的名称部分可以用person."name"person.'name'引用。当某些标识符包含Java语言规范禁止的非法字符,但在引用时Groovy允许使用的非法字符时,这尤其有趣。例如,破折号,空格,感叹号等字符。

def map = [:]

map."an identifier with a space and double quotes" = "ALLOWED"
map.'with-dash-signs-and-single-quotes' = "ALLOWED"

assert map."an identifier with a space and double quotes" == "ALLOWED"
assert map.'with-dash-signs-and-single-quotes' == "ALLOWED"
     

正如我们将在以下有关字符串的部分中看到的那样,Groovy提供了不同的字符串文字。实际上在点后允许使用所有类型的字符串:

map.'single quote'
map."double quote"
map.'''triple single quote'''
map."""triple double quote"""
map./slashy string/
map.$/dollar slashy string/$
     

纯字符串和Groovy的GStrings(插值字符串)之间存在差异,因为在后一种情况下,将插值插入最终字符串中以评估整个标识符:

def firstname = "Homer"
map."Simpson-${firstname}" = "Homer Simpson"

assert map.'Simpson-Homer' == "Homer Simpson"
     
     

来源:https://groovy-lang.org/syntax.html#_quoted_identifiers

如果要使用带引号的标识符,则必须将所有值存储在映射中,例如:

def map = [:]
map."trigger-${cname}" = true

assert map."trigger-${cname}"
本文链接:https://www.f2er.com/3144874.html

大家都在问