简体   繁体   English

在 Groovy 中创建字符串列表

[英]Create String list in Groovy

The following code in Groovy adds GString s to the list: Groovy 中的以下代码将GString添加到列表中:

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

When I create a ProcessBuilder with this list, I get a ClassCastException .当我使用此列表创建ProcessBuilder时,我得到一个ClassCastException What's a groovy way to coerce the list elements to the correct type?将列表元素强制为正确类型的 groovy 方法是什么?

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?实际上,您为什么出于兴趣使用 ProcessBuilder ? Groovy adds ways to do process management , and even adds three execute methods to List Groovy 增加了进行进程管理的方法,甚至在 List 中增加了三个execute方法

You can do (this is on OS X or Linux):你可以这样做(这是在 OS X 或 Linux 上):

def opt = '-a'

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

which prints out the files in my /tmp folder打印出我的/tmp文件夹中的文件

Try尝试

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

because the later is a GString .因为后者是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: output 是:

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.应该做到这一点,但我不是 100% 确定这是最好的方法。

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

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