4

I'd like something like the following to work:

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

What library do I need to use?

(somewhat related to this.)

einpoklum
  • 118,144
  • 57
  • 340
  • 684

3 Answers3

2

(based on @fge's answer.)

One can use JCommander with statics:

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);
    }
}
Community
  • 1
  • 1
einpoklum
  • 118,144
  • 57
  • 340
  • 684
1

You can try klab-commons-cli, it adds annotations to Apache commons-cli; there is no distribution jar, you just use the source code. An alternative, which doesn't leverage commons-cli, but provides a distribution library, is args4j.

einpoklum
  • 118,144
  • 57
  • 340
  • 684
remigio
  • 4,101
  • 1
  • 26
  • 28
1

JCommander may be of some use to you. It uses annotations to describe all command line arguments and generates options/help text for you.

Quoting the example found on the web site:

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;
}
fge
  • 119,121
  • 33
  • 254
  • 329
  • And will this work with static variables as well? I only need to run the main method in my app class... – einpoklum Feb 03 '13 at 17:10
  • Not that I know of... But you can just do `new Main()` in your `main()` method and run it. You will only have one instance at run time, so that's no big deal. – fge Feb 03 '13 at 17:44