Create String list in Groovy

Aaron Digulla picture Aaron Digulla · Jul 6, 2011 · Viewed 43.8k times · Source

The following code in Groovy adds GStrings to the list:

List<String> args = [ 'cmd', "-Dopt=${value}" ]

When I create a ProcessBuilder with this list, I get a ClassCastException. What's a groovy way to coerce the list elements to the correct type?

Answer

tim_yates picture tim_yates · Jul 6, 2011

Or, you can do:

List<String> args = [ 'cmd', "-Dopt=${value}"] as String[]

or

List<String> args = [ 'cmd', "-Dopt=${value}"]*.toString()

actually, why are you using ProcessBuilder out of interest? Groovy adds ways to do process management, and even adds three execute methods to List

You can do (this is on OS X or Linux):

def opt = '-a'

println( [ 'ls', "$opt" ].execute( null, new File( '/tmp' ) ).text )

which prints out the files in my /tmp folder