views:

676

answers:

4

I write a little command-line-application in Java. This application should work with a mix of parameters and commands, a little bit similar to the 'svn'-command.

Examples:

app url command1
app url command2 --parameter2 -x
app url command1 --param-with-argument argument
app --parameter url command1
app --no-url command2
app --help

Exists an easy to use library for Java that supports the parsing of such command-lines and probably also supports me by creating automatically an appropriate help?

+8  A: 

I'm a fan of Commons CLI.

You can set it to understand commands, flags (with short and long names), whether or not certain commands/switches are required, or if they have default values. It even has functionality to print out a useful --help type message.

The Usage Scenarios page has some good examples of how it can be used.

matt b
+2  A: 

There is also a java getopt http://www.urbanophile.com/arenn/hacking/download.html

Clint
+5  A: 

Try args4j: https://args4j.dev.java.net/.

I prefer args4j to Common CLI (used both of them). With args4j you don't need to query any functions. Everything is done for you - parameters are set to object fields via reflection.

Vitaly
A: 

JewelCLI is a Java library for command-line parsing that yields clean code. It uses Proxied Interfaces Configured with Annotations to dynamically build a type-safe API for your command-line parameters.

An example parameter interface Person.java:

import uk.co.flamingpenguin.jewel.cli.Option;

public interface Person {
    @Option String getName();
    @Option int getTimes();
}

An example usage of the parameter interface Hello.java:

import static uk.co.flamingpenguin.jewel.cli.CliFactory.parseArguments;
import uk.co.flamingpenguin.jewel.cli.ArgumentValidationException;

public class Hello {
    public static void main(String [] args) {
        try {
            Person person = parseArguments(Person.class, args);
            for (int i = 0; i < person.getTimes(); i++)
                System.out.println("Hello " +  person.getName());
        } catch(ArgumentValidationException e) {
            System.err.println(e.getMessage());
        }
    }
}

Save copies of the files above to a single directory and download the JewelCLI 0.6 JAR to that directory as well.

Compile and run the example in Bash on Linux/Mac OS X/etc.:

javac -cp jewelcli-0.6.jar:. Person.java Hello.java
java -cp jewelcli-0.6.jar:. Hello --name="John Doe" --times=3

Compile and run the example in the Windows Command Prompt:

javac -cp jewelcli-0.6.jar;. Person.java Hello.java
java -cp jewelcli-0.6.jar;. Hello --name="John Doe" --times=3

Running the example should yield the following output:

Hello John Doe
Hello John Doe
Hello John Doe
Alain O'Dea
As you can see JewelCLI makes command-line parsing simple and type safe. It also has no dependency baggage to drag along which is a rarity these days.
Alain O'Dea