Java: Passing combination of named and unnamed parameters to executable Jar/Main Method

别等时光非礼了梦想. 提交于 2019-12-06 07:21:25

Apache Commons CLI is what I use to parse java command line arguments. Examples can be found here and can be used to do any of the following option formats:

  • POSIX like options (ie. tar -zxvf foo.tar.gz)
  • GNU like long options (ie. du --human-readable --max-depth=1)
  • Java like properties (ie. java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo)
  • Short options with value attached (ie. gcc -O2 foo.c)
  • long options with single hyphen (ie. ant -projecthelp)

Based on @Mac70's answer and a few additions,

private static Map<String, String> map;
private static void makeMap(String[] args) {
    map = new HashMap<>();
    for (String arg : args) {
        if (arg.contains("=")) {
            //works only if the key doesn't have any '='
            map.put(arg.substring(0, arg.indexOf('=')),
                    arg.substring(arg.indexOf('=') + 1));
        }
    }
}

public static void main(String[] args) {
    makeMap(args);

    //.. 
    String param3 = map.get("param3name");
    String param1 = map.get("param1name");
}

If you need anything extensive, you need to look at @Archangel33's answer.

As long as params and names don't contain spaces - you can get all of them, split at "=" key and add key/value pairs to the HashMap. Later you can just get any value you want using key.

Edit: If you want to not add some elements to the map, then you can ignore them if these elements don't contain "=" key.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!