开发者

Create String list in Groovy

开发者 https://www.devze.com 2023-03-18 19:39 出处:网络
The following code in Groovy adds GStrings to the list:开发者_如何学运维 List<String> args = [ \'cmd\', \"-Dopt=${value}\" ]

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?


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


Try

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

because the later is a GString.


I did a test:

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

System.out.println (args.getClass());

System.out.println (args.get(0).getClass());
System.out.println (args.get(1).getClass());

The output was:

class java.util.ArrayList
class java.lang.String
class org.codehaus.groovy.runtime.GStringImpl

Changing the code a bit to be:

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

System.out.println (args.getClass());

System.out.println (args.get(0).getClass());
System.out.println (args.get(1).getClass());

produced this:

class java.util.ArrayList
class java.lang.String
class java.lang.String

Should do the trick, but I'm not 100% sure this is the best way to do it.

0

精彩评论

暂无评论...
验证码 换一张
取 消