Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / Java
Tip/Trick

Argument Parser

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
27 Nov 2012CPOL 13.2K   4   2
A simple method to parse an argument list as a name value pair

Introduction

Simply put, I often need to parse the arguments for a Java app and I always use a name value pair. After the 7th time of writing the same thing inside main, I moved it out into a simple method.

Using the code

The arguments are passed into the method and out comes a Map at the other side. 

Java
/**
 * Parse a string array of arguments into a map.
 * Takes an array of arguments and splits them into a map of name/value pairs.
 * Each argument name must be unique and prefixed by - and have a single value.
 * Example:
 * -debug TRUE -name "William Norman-Walker" -number 7
 * @param args  An array of arguments containing name/value pairs.
 * @return      The arguments as a map.
 * @throws IllegalArgumentException
 *              thrown when the arguments are in an incorrect format.
 */
static public Map<String, String> parseArguments(String[] args) {
    Map<String, String> argMap = new HashMap<String, String>();
    String key = null;
    int a = 1;
    while (a < args.length) {
        if (key==null) {
            if (args[a].startsWith("-")) {
                key = args[a].substring(1).toLowerCase();
                if (argMap.containsKey(key)) {
                    throw new IllegalArgumentException
                            ("Duplicate argument");
                }
            } else {
                throw new IllegalArgumentException
                        ("Argument names must begin with -");
            }
        } else {
            argMap.put(key, args[a]);
            key = null;
        }
        a++;
    }
    if (key != null) {
        throw new IllegalArgumentException
                ("Argument without value");
    }
    return argMap;
} 

That is really it. I use it like this:

Java
public static void main(String[] args) {
    Map<string,> options = ArgumentList.parseArguments(args);

    String config = options.remove("config");
    if (config == null) {
        throw new IllegalArgumentException("No configuration supplied, use -config option");
    }
    String loggingOptions = options.remove("log");
    if (!options.isEmpty()) {
        throw new IllegalArgumentException("Invalid option in argument list.");
    }
    // code goes here...
}

Removing each item and checking nothing is left at the end.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
President Belligerent Bad Tempered Old Fools Club
United Kingdom United Kingdom
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionstatement is incorrect Pin
swong88827-Nov-12 15:18
swong88827-Nov-12 15:18 
AnswerRe: statement is incorrect Pin
Nagy Vilmos27-Nov-12 22:13
professionalNagy Vilmos27-Nov-12 22:13 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.