--key=value 格式的 Java 命令行参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/21322384/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 08:02:56  来源:igfitidea点击:

Java command line arguments in --key=value format

javacommand-line

提问by user797963

Is there a smart/easy way to use command line arguments in the --key=value format? I just quickly threw together a check for args[i] to see if it contains one of my keys, then grab the value for that key and set a variable for it, but there's gotta be a better way. I can't seem to find anything good with googling, so I must be searching the wrong thing. Any ideas/insight?

是否有一种智能/简单的方法来使用 --key=value 格式的命令行参数?我只是快速地检查 args[i] 以查看它是否包含我的一个键,然后获取该键的值并为其设置一个变量,但必须有更好的方法。我似乎无法通过谷歌搜索找到任何好的东西,所以我一定是在搜索错误的东西。任何想法/见解?

Thanks!

谢谢!

采纳答案by user797963

Try the -Doption, allows to set key=valuepair:

试试这个-D选项,允许设置key=value对:

run command; note there are no space between -Dkey

运行命令;注意中间没有空格-Dkey

  • java -Dday=Friday -Dmonth=Jan MainClass
  • java -Dday=Friday -Dmonth=Jan MainClass

In your code:

在您的代码中:

String day = System.getProperty("day");
String month = System.getProperty("month");

回答by 18446744073709551615

This transforms String[] argswith key=valuepairs into a Map. HashMapis used here because it allows null values.

这将String[] args使用key=value对转换为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()+";");
        }
    }

}

Example run:

示例运行:

$ 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)

Above, an Exception has happened because there is no "get"in the defaults.

上面,发生了异常,因为"get"默认值中没有。

If we use uncheckedMapOfArgs()instead of mapOfArgs():

如果我们使用uncheckedMapOfArgs()代替mapOfArgs()

$ java org.company.Main get
what => hello;
get => null;
who => world;

回答by Amar Prakash Pandey

As of now, there is no way to convert --key=valueto Map instead of String.

到目前为止,还没有办法转换--key=value为 Map 而不是 String。

public static void main(String[] args) {

    HashMap<String, String> params = convertToKeyValuePair(args);

    params.forEach((k, v) -> System.out.println("Key : " + k + " Value : " + v));

}

private static HashMap<String, String> convertToKeyValuePair(String[] args) {

    HashMap<String, String> params = new HashMap<>();

    for (String arg: args) {

        String[] splitFromEqual = arg.split("=");

        String key = splitFromEqual[0].substring(2);
        String value = splitFromEqual[1];

        params.put(key, value);

    }

    return params;
}

Hope this helps!

希望这可以帮助!