Last active
September 18, 2017 09:25
-
-
Save artem-smotrakov/ce9f0634d3851515c265af03eaa9f6ca to your computer and use it in GitHub Desktop.
How to parse command line arguments in Java. For more details see https://codeandsolder.blogspot.com/2017/09/how-to-parse-command-line-arguments-in-java.html
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.HashMap; | |
import java.util.Map; | |
public class CommandLine { | |
public static Parameters parse(String[] args) { | |
Parameters params = new Parameters(); | |
int i = 0; | |
while (i < args.length) { | |
switch(args[i]) { | |
case "--host": | |
if (i == args.length - 1) { | |
throw new RuntimeException("No path specified for --host option"); | |
} | |
params.add("host", args[++i]); | |
break; | |
case "--port": | |
if (i == args.length - 1) { | |
throw new RuntimeException("No path specified for --port option"); | |
} | |
params.add("port", Integer.parseInt(args[++i])); | |
break; | |
case "--verbose": | |
params.add("verbose", Boolean.TRUE); | |
break; | |
default: | |
throw new RuntimeException("Unexpected parameter: " + args[i]); | |
} | |
i++; | |
} | |
return params; | |
} | |
public static class Parameters { | |
private final Map<String, Object> params = new HashMap<>(); | |
public void add(String name, Object value) { | |
params.put(name, value); | |
} | |
public String getString(String name, String defaultValue) { | |
Object value = params.get(name); | |
if (value == null) { | |
return defaultValue; | |
} | |
if (value instanceof String) { | |
return (String) value; | |
} | |
throw new RuntimeException( | |
String.format("'%s' doesn't look like a string: %s", name, value)); | |
} | |
public int getInteger(String name, int defaultValue) { | |
Object value = params.get(name); | |
if (value == null) { | |
return defaultValue; | |
} | |
if (value instanceof Integer) { | |
return (Integer) value; | |
} | |
throw new RuntimeException( | |
String.format("'%s' doesn't look like an integer: %s", name, value)); | |
} | |
public boolean getBoolean(String name, boolean defaultValue) { | |
Object value = params.get(name); | |
if (value == null) { | |
return defaultValue; | |
} | |
if (value instanceof Boolean) { | |
return (Boolean) value; | |
} | |
throw new RuntimeException( | |
String.format("'%s' doesn't look like an integer: %s", name, value)); | |
} | |
} | |
public static void main(String[] args) { | |
Parameters params = parse(args); | |
System.out.println("host = " + params.getString("host", "localhost")); | |
System.out.println("port = " + params.getInteger("port", 80)); | |
System.out.println("verbose = " + params.getBoolean("verbose", false)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment