Skip to content

Command Line Arguments for Java Programs

October 17, 2016

Introduction

When building Java projects you may the need to pass in arguments into a program so you can control certain parts of the execution. To do this there’s a simple way and a more complete way that allows you to more dynamically specify arguments in any order. This post will include examples on how you can support passing in arguments into a Java program.

Simple Example

The most simple method of accepting arguments into your application is to use the default args (String array) that you have to provide in the main function in the Main class.

If you want to use this method its as simple as assuming that each desired argument is at a specific position within the array.

Code

com.example.args_example.java.Main.java

package com.example.args_example.java;
public class Main {
    public static void main(String[] args) {
        System.out.println(java.util.Arrays.toString(args));
    }
}

Running

$ java -cp args-example.jar com.example.args_example.java.Main arg1 arg2 arg3

[arg1, arg2, arg3]

Disadvantages

The simple case is great because it doesn’t require a lot of code and you get exactly what you need from what you’re given right off the bat. However, there are limitations to this approach. The arguments that you provide need to be in a specific order and you can’t optionally drop any arguments without severely complicating your arguments parser.

Complete Example

If you come across the case where you would like to allow the user to provide optional arguments, provide the arguments in any particular order, and validate the arguments then this approach is more your speed.

Here, we’re building out a separate class to store the arguments and provide specialized functions for its validation and retrieval.

com.example.args_example.java.Main.java

package com.example.args_example.java;
import org.kohsuke.args4j.CmdLineException;
import java.util.List;
public class Main {
    public static void main(String[] args) throws CmdLineException {
        List argsList =java.util.Arrays.asList(args);
        if(argsList.contains("-help") || argsList.contains("--help")) {
            MainArgs.printUsage();
            System.exit(0);
        }
        MainArgs mainArgs = new MainArgs(args);
        System.out.println(mainArgs.toString());
    }
}

com.example.args_example.java.MainArgs.java

package com.example.args_example.java;

import org.kohsuke.args4j.CmdLineException;
import org.kohsuke.args4j.CmdLineParser;
import org.kohsuke.args4j.Option;

public class MainArgs {

    @Option(name="-strArg", usage="Example of a String Argument. (Required)", required = true)
    private String strArg;

    @Option(name="-intArg", usage="Example of an Integer argument.")
    private int intArg;

    @Option(name="-bolArg", usage="Example of a Boolean argument.")
    private boolean bolArg;

    public MainArgs() {}

    public MainArgs(String... args) throws CmdLineException {
        CmdLineParser parser = getCmdLineParser();
        try {
            parser.parseArgument(args);
        } catch (CmdLineException e) {
            System.err.println(e.getMessage());
            printUsage();
            throw e;
        }
    }

    public CmdLineParser getCmdLineParser() {
        return new CmdLineParser(this);
    }

    public static void printUsage() {
        CmdLineParser parser = new MainArgs().getCmdLineParser();
        parser.printUsage(System.err);
    }

    public String getStrArg() {
        return strArg;
    }

    public void setStrArg(String strArg) {
        this.strArg = strArg;
    }

    public int getIntArg() {
        return intArg;
    }

    public void setIntArg(int intArg) {
        this.intArg = intArg;
    }

    public boolean isBolArg() {
        return bolArg;
    }

    public void setBolArg(boolean bolArg) {
        this.bolArg = bolArg;
    }

    @Override
    public String toString() {
        return "MainArgs{" +
                "strArg='" + strArg + '\'' +
                ", intArg=" + intArg +
                ", bolArg=" + bolArg +
                '}';
    }
}

Running

$ java -cp args-example.jar com.example.args_example.java.Main -help

-bolArg : Example of a Boolean argument. (default: false)
-intArg N : Example of an Integer argument. (default: 0)
-strArg VAL : Example of a String Argument. (Required)

$ java -cp args-example.jar com.example.args_example.java.Main

Option “-strArg” is required
-bolArg : Example of a Boolean argument. (default: false)
-intArg N : Example of an Integer argument. (default: 0)
-strArg VAL : Example of a String Argument. (Required)

$ java -cp args-example.jar com.example.args_example.java.Main -strArg test

MainArgs{strArg=’test’, intArg=0, bolArg=false}

$ scala -classpath args-example.jar com.example.args_example.scala.Main -strArg test -intArg 100

MainArgs{strArg=’test’, intArg=100, bolArg=false}

$ java -cp args-example.jar com.example.args_example.java.Main -strArg test -intArg 100 -bolArg

MainArgs{strArg=’test’, intArg=100, bolArg=true}

Equivalent in other Languages

Scala

https://softwaresanders.wordpress.com/2016/10/11/command-line-arguments-for-scala-programs/

Python

To Be Created

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: