如何使用注释自动解析我的命令行参数?

时间:2013-02-03 11:08:14

标签: java parsing command-line annotations arguments

我希望以下内容能够发挥作用:

public class A {
    @command_line_arg{"argname1"}
    static boolean x;

    @command_line_arg{"argname2"}
    static List<String> y;

    void main(String[] args) {
        /* perhaps a call such as parseArgs(); here */
        System.out.println("got argname1 = " + x);
        System.out.println("got argname2 = " + y);
    }
}

我需要使用哪个库?

(与this有些相关。)

3 个答案:

答案 0 :(得分:2)

(基于@ fge的answer。)

可以使用JCommander静态:

public class A {

    @Parameter(names = "-argname1")
    static boolean x;
    @Parameter(names = "-argname2", variableArity = true)
    static List<String> y;

    @Parameter
    public static List<String> remainingParameters;

    void main(String[] args) {
        new JCommander(A.class.newInstance(), args);
        System.out.println("got argname1 = " + x);
        System.out.println("got argname2 = " + y);
    }
}

答案 1 :(得分:1)

您可以尝试klab-commons-cli,它会为Apache commons-cli添加注释;没有分发jar,你只需使用源代码。另一种不利用commons-cli但提供分发库的替代方法是args4j

答案 2 :(得分:1)

JCommander可能会对您有所帮助。它使用注释来描述所有命令行参数,并为您生成选项/帮助文本。

引用网站上的示例:

public class JCommanderExample {
  @Parameter
  private List<String> parameters = new ArrayList<String>();

  @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;
}