list 在 Groovy 中创建字符串列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6592716/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Create String list in Groovy
提问by Aaron Digulla
The following code in Groovy adds GString
s to the list:
Groovy 中的以下代码将GString
s添加到列表中:
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?
当我ProcessBuilder
用这个列表创建一个时,我得到一个ClassCastException
. 将列表元素强制为正确类型的常规方法是什么?
回答by tim_yates
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
实际上,您为什么出于兴趣使用 ProcessBuilder?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
文件夹中的文件
回答by Erich Kitzmueller
回答by RonK
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.
应该做到这一点,但我不是 100% 确定这是最好的方法。