简体   繁体   中英

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

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

I am passing this variable in a method verifyFields(listOfAllFields) and the method implementation is

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 .

you just use list literal for that

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

then you can use a spread operator to pass it into the method:

verifyFields( *listOfAllFields )

If your constant is a String as opposed to a List, the split method should suffice.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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