这会将带有 key=value 对的 String[] args 转换为 Map。此处使用HashMap,因为它允许空值。
package org.company;
import java.util.HashMap;
import java.util.Map;
public class Main {
/**
* Convert an array of key=value pairs into a hashmap.
* The string "key=" maps key onto "", while just "key" maps key onto null.
* The value may contain '=' characters, only the first "=" is a delimiter.
* @param args command-line arguments in the key=value format (or just key= or key)
* @param defaults a map of default values, may be null. Mappings to null are not copied to the resulting map.
* @param allowedKeys if not null, the keys not present in this map cause an exception (and keys mapped to null are ok)
* @return a map that maps these keys onto the corresponding values.
*/
static private HashMap<String, String> _parseArgs(String[] args, HashMap<String, String> defaults, HashMap<String, String> allowedKeys) {
// HashMap allows null values
HashMap<String, String> res = new HashMap<>();
if (defaults != null) {
for (Map.Entry<String, String> e : defaults.entrySet()) {
if (e.getValue() != null) {
res.put(e.getKey(),e.getValue());
}
}
}
for (String s: args) {
String[] kv = s.split("=", 2);
if (allowedKeys != null && !allowedKeys.containsKey(kv[0])) {
throw new RuntimeException("the key "+kv[0]+" is not in allowedKeys");
}
res.put(kv[0], kv.length<2 ? null : kv[1]);
}
return res;
}
/**
* Compose a map to serve as defaults and/or allowedKeys for _parseArgs().
* The string "key=" maps key onto "" that becomes the default value for the key,
* while just "key" maps key onto null which makes it a valid key without any default value.
* The value may contain '=' characters, only the first "=" is a delimiter.
* @param args Strings in "key=value" (or "key=", or just "key") format.
* @return a map that maps these keys onto the corresponding values.
*/
static public HashMap<String, String> defaultArgs(String... args) {
return _parseArgs(args, null, null);
}
/**
* Convert an array of strings in the "key=value" format to a map.
* If defaults is not null, the keys not present in this map cause an exception (and keys mapped to null are ok).
* @param args the array that main(String[]) received
* @param defaults specifies valid keys and their default values (keys mapped to null are valid, but have no default value)
* @return a map that maps these keys onto the corresponding values.
*/
static public HashMap<String, String> mapOfArgs(String[] args, HashMap<String, String> defaults) {
return _parseArgs(args, defaults, defaults);
}
/**
* Convert an array of strings in the "key=value" format to a map.
* The keys not present in defaults are always ok.
* @param args the array that main(String[]) received
* @param defaults if not null, specifies default values for keys (keys mapped to null are ignored)
* @return a map that maps these keys onto the corresponding values.
*/
static public HashMap<String, String> uncheckedMapOfArgs(String[] args, HashMap<String, String> defaults) {
return _parseArgs(args, defaults, null);
}
/**
* Test harness
* @param args
*/
public static void main(String[] args) {
Map<String, String> argMap = mapOfArgs(args, defaultArgs("what=hello","who=world","print"));
for (Map.Entry<String,String> e : argMap.entrySet()) {
System.out.println(""+e.getKey()+" => "+e.getValue()+";");
}
}
}
示例运行:
$ java org.company.Main
what => hello;
who => world;
$ java org.company.Main print=x=y
print => x=y;
what => hello;
who => world;
$ java org.company.Main who=lambdas what=rule print
print => null;
what => rule;
who => lambdas;
$ java org.company.Main who=lambdas what=rule print=
print => ;
what => rule;
who => lambdas;
$ java org.company.Main get
Exception in thread "main" java.lang.RuntimeException: the key get is not in allowedKeys
at org.company.Main._parseArgs(Main.java:37)
at org.company.Main.mapOfArgs(Main.java:64)
at org.company.Main.main(Main.java:9)
上面,发生了异常,因为默认值中没有"get"。
如果我们使用uncheckedMapOfArgs() 而不是mapOfArgs():
$ java org.company.Main get
what => hello;
get => null;
who => world;