Skip to content
Jason Robinson edited this page Jun 3, 2015 · 3 revisions

Welcome to the args4j wiki!

Sample code for how to use Args4J has been provided on the author's website here: http://args4j.kohsuke.org/sample.html.

The content is being copy / pasted below so it is retained with the source code repository. Specific jar file references have been updated to the latest release (args4j-2.32.jar as of 2015/06/02).


Prepare your environment

Because we only want to have a very small example, we use only one single directory containing all the stuff— sources, class files and the args4j jarfile. You need a JDK 1.5 or higher.

  1. Create a directory args4j-sample this will be our project directory.
  2. Download the latest args4j version from the download page
  3. Extract the args4j-version.jar from the archive into the project directory

Implementing pure business logic

Create the business bean Business.java. At this point, it only contains the business logic. To run this logic, we want a run() method.

import java.io.File;
public class Business {
    public String name;
    public File file;

    public void setFile(File f) { 
        if (f.exists()) file = f; 
    }

    public void run() {
        System.out.println("Business-Logic");
        System.out.println("- name: " + name);
        System.out.println("- file: " + ((file!=null) 
                                      ? file.getAbsolutePath() 
                                      : "null"));
}
}

Compile the sources javac -classpath .;args4j-2.32.jar Business.java


Start the class

Now we have three options for setting the field from the command line:

  1. implement a main-method and the command line parsing for our own
  2. implement a main-method and use args4j for parsing
  3. use the starter class

Okay...because this is a sample, the first method isn't the right solution here ;-) In the first step we just use the Starter.

Start the class

java -classpath .;args4j-2.32.jar -Dmainclass=Business org.kohsuke.args4j.Starter and we get

Business-Logic
- name: null
- file: null

What happened? The starter class had a look into the Java system property mainclass loads that class, instantiates it, and executes their run() method. We provide the classpath so the Java VM could find the starter class and our business class.

Next, let's try to start the class with arguments:

java -classpath .;args4j-2.32.jar -Dmainclass=Business org.kohsuke.args4j.Starter -name "Hrld" -file args4j-2.32.jar

which results in

"-name" is not a valid option
Business

Adding Args4J Annotations

Well, we don't have any annotations to handle the command line parameters yet. Let's fix that:

    ...
    import org.kohsuke.args4j.Option;
    ...
    @Option(name="-name",usage="Sets a name")
    public String name;
    ...
    @Option(name="-file",usage="Sets a file if that is present")
    public void setFile(File f) { 
    ...

Recompile and try the start again

Business-Logic
- name: Hello World
- file: C:\temp\args4j-sample\args4j-2.32.jar

So far so good.

What is with wrong parameters?

java -classpath .;args4j-2.32.jar -Dmainclass=Business org.kohsuke.args4j.Starter -wrong

which outputs

"-wrong" is not a valid option
Business [options]
 -file FILE : Sets a file if that is present
 -name VAL  : Sets a name

Again—what happened?

args4j throws a CmdLineException when we wrote an incorrect parameter (-wrong). The starter class catches this and prints a help message: the classname and an [Option] (since we have some @Options in the code). (Since we don't have an @Argument, that line is not Business [options] arguments.)

Then it shows the possible options, as given by the parser's printUsage() method.

As you can see, we added an @Option to an attribute and to a setter method. Using this with attributes is the simplest way to use args4j. But if you wanted to do some checks (e.g. our file existence check), you could add the annotation to a setter.


Enhancing the parsing

If you want to have more control over parsing and error handling, don't use the starter. Use CmdLineParser directly.

Here are the main steps:

    import org.kohsuke.args4j.CmdLineParser;
    import org.kohsuke.args4j.CmdLineException;
    ...
    public static void main(String[] args) {
        Business bean = new Business();
        CmdLineParser parser = new CmdLineParser(bean);
        try {
                parser.parseArgument(args);
                bean.run();
        } catch (CmdLineException e) {
            // handling of wrong arguments
            System.err.println(e.getMessage());
            parser.printUsage(System.err);
        }
    }

Since we're not using the Starter, we also have to supply the main method and start it. So, after compiling, we could start that with:

java -classpath .;args4j-2.32.jar Business -name "Hello World" -file args4j-2.32.jar

and we get

Business-Logic
- name: Hello World
- file: C:\temp\args4j-sample\args4j-2.32.jar

The error case from above

java -classpath .;args4j-2.32.jar Business -wrong

results in

"-wrong" is not a valid option
 -file FILE : Sets a file if that is present
 -name VAL  : Sets a name
Clone this wiki locally