1

我正在尝试使用 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)

我错过了什么?

4

2 回答 2

1

您可能知道groovy. 在java中,{ ..}被使用。在 groovy 中如下:

def list = [1, 2]

更改自:

@Parameter(names = { "-log", "-verbose" }, description = "Level of verbosity")

至:

@Parameter(names = ["-log", "-verbose" ] , description = "Level of verbosity")
于 2017-06-19T08:52:10.873 回答
0

Here's the solution that I copied to my snippets collection:

Sample Groovy Script for jCommander

#!/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";
  }
}
于 2017-06-20T08:31:18.893 回答