简体   繁体   English

将逗号分隔的字符串常量传递给 groovy 中的方法

[英]Passing a comma separate String constant to a method in groovy

I am new to Groovy and need to achieve following, I have defined a constant as我是 Groovy 的新手,需要实现以下目标,我将常量定义为

static String listOfAllFields = "Field1","Field2","Field3"

I am passing this variable in a method verifyFields(listOfAllFields) and the method implementation is我在方法verifyFields(listOfAllFields)传递这个变量,方法实现是

def verifyFields(String... fields) {
  fields.each {
    //do something
  }
}

if I pass like this verifyFields("Field1","Field2,"Field3") the method works but if I have to pass these through a variable, how do I achieve? how do I pass the "," separated values as a List in groovy to listOfAllFields .如果我像这样传递verifyFields("Field1","Field2,"Field3")该方法有效,但如果我必须通过变量传递这些,我该如何实现?如何将“,”分隔值作为列表传递在 groovy 到listOfAllFields

you just use list literal for that您只需为此使用list literal

static listOfAllFields = [ "Field1","Field2","Field3" ]

then you can use a spread operator to pass it into the method:然后您可以使用spread operator将其传递给方法:

verifyFields( *listOfAllFields )

If your constant is a String as opposed to a List, the split method should suffice.如果您的常量是 String 而不是 List, split方法就足够了。

static final String ALL_FIELDS = 'Field1,Field2,Field3'
verifyFields(ALL_FIELDS.split(','))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM