我正在尝试使用jCommander解析Groovy中的命令行参数。
(MacBook(El Capitan),Groovy 2.4.11,jCommander-1.49)
jCommander.org上提供的示例(请参阅http://jcommander.org/#_groovy)读取:
import com.beust.jcommander.Parameter;
public class Args {
@Parameter
private List<String> parameters = new ArrayList<>();
@Parameter(names = { "-log", "-verbose" }, description = "Level of verbosity")
private Integer verbose = 1;
@Parameter(names = "-groups", description = "Comma-separated list of group names to be run")
private String groups;
@Parameter(names = "-debug", description = "Debug mode")
private boolean debug = false;
}
但是当我尝试运行该代码( groovy jCommanderSample.groovy )时,我得到:
lexu@mbp:~/.../Groovy/CliParameters $ groovy jCommanderSample.groovy
Caught: groovy.lang.MissingMethodException: No signature of method: static com.beust.jcommander.JCommander.newBuilder() is applicable for argument types: () values: []
groovy.lang.MissingMethodException: No signature of method: static com.beust.jcommander.JCommander.newBuilder() is applicable for argument types: () values: []
at jCommanderSample$_run_closure1.doCall(jCommanderSample.groovy:9)
at jCommanderSample.run(jCommanderSample.groovy:8)
我错过了什么?
答案 0 :(得分:1)
您可能会发现groovy
中的列表定义存在差异。
在java中,使用{ ..}
。在groovy中如下:
def list = [1, 2]
更改自:
@Parameter(names = { "-log", "-verbose" }, description = "Level of verbosity")
要:
@Parameter(names = ["-log", "-verbose" ] , description = "Level of verbosity")
答案 1 :(得分:0)
这是我复制到我的代码段集合的解决方案:
jCommander的Groovy脚本示例
#!/usr/bin/env groovy
import com.beust.jcommander.*
class Simple {
static class Args {
@Parameter
private List<String> aParamList = [];
@Parameter(names = [ "--quiet", "-q" ], description = "quiet mode, no output to STDOUT")
private Boolean aQuiet = false;
@Parameter(names = [ "--logging", "-l" ], description = "logging verbosity (0-4)")
private Integer aLogLevel = 1;
@Parameter(names = [ "--group", "-g" ], description = "group name, default is 'none'")
private String aGroupName = 'none';
}
public static main(String[] pArgs) {
Boolean vQuiet ;
Integer vLogLevel ;
String vGroupName ;
List<String> vParamList;
new Args().with {
try {
new JCommander(it, pArgs)
vQuiet = it.aQuiet;
vLogLevel = it.aLogLevel;
vGroupName = it.aGroupName;
vParamList = it.aParamList;
}
catch(com.beust.jcommander.ParameterException e) {
println "Fatal Error parsing arguments: $e.message"
System.exit(-1)
}
}
println "unbound parameters: " + vParamList;
println " LogLevel: $vLogLevel";
println " Silent Mode: $vQuiet";
println " GroupName: $vGroupName";
}
}