I want to pass, both, named and unnamed arguments to the main method.
Currently I am passing arguments as:
java -jar myfile.jar param1 param2
and handling them as:
public static void main(String[] args) throws IOException {
String param1 = args[0];
String param2 = args[1];
}
However, I want to pass the arguments in a more dynamic way - namely, so that:
Passing in a way Something like this:
java -jar myJar param3name=param3 param2name=param2 param1name=param1 param5 param6
and handling in a way something like this:
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 am fine to work with some external libraries which would make my work easier.
I have already seen this and it is not comprehensive.
Any input on how to accomplish the task?
Command-line arguments in Java are used to pass arguments to the main program. If you look at the Java main method syntax, it accepts String array as an argument. When we pass command-line arguments, they are treated as strings and passed to the main function in the string array argument.
Run a Nonexecutable JAR with Arguments To run an application in a nonexecutable JAR file, we have to use -cp option instead of -jar. We'll use the -cp option (short for classpath) to specify the JAR file that contains the class file we want to execute: java -cp jar-file-name main-class-name [args …]
Internally, JVM wraps up these command-line arguments into the args[ ] array that we pass into the main() function. We can check these arguments using args. length method. JVM stores the first command-line argument at args[0], the second at args[1], the third at args[2], and so on.
When you pass an argument by name, you specify the argument's declared name followed by a colon and an equal sign ( := ), followed by the argument value. You can supply named arguments in any order. When you call this procedure, you can supply the arguments by position, by name, or by using a mixture of both.
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:
tar -zxvf foo.tar.gz
)du --human-readable --max-depth=1
)java -Djava.awt.headless=true -Djava.net.useSystemProxies=true Foo
)gcc -O2 foo.c
)ant -projecthelp
)If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With