I am looking for a way so that we can pass both named and unnamed arguments to the main method. Currently I am passing them as follows
java -jar myJar param1 param2 param3
and handling them as
public static void main( String[] args ) throws IOException
{
String param1 = args[0];
String param2=args[1];
.....
I must be able to send them and handle them as below in Java so that I can read the values based on their names and need not pass the arguments in the same order everytime I execute the Main method. I am fine to work with some external libraries which would make my work easier.
I am want to send my arguments as below and handle it in java main
java -jar myJar param3name=param3 param2name=param2 param1name=param1 param5 param6
and I want to handle them as something below
public static void main( String[] args ) throws IOException
{
//something like
String param3 = getvaluemethod("param3name");
String param1 = getvaluemethod("param1name");
.....
String Param5 =args[n]
String param6 = args[n+1]
.....
I have already seen this link and is not comprehensive. Any input on how to accomplish the task?
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.
来源:https://stackoverflow.com/questions/24891990/java-passing-combination-of-named-and-unnamed-parameters-to-executable-jar-main