A command-line argument is an information that directly follows the program's name on the command line when it is executed. To access the command-line arguments inside a Java program is quite easy. They are stored as strings in the String array passed to main( ).
When a parameter is passed to the method, it is called an argument. So, from the example above: fname is a parameter, while Liam , Jenny and Anja are arguments.
A command line argument (or parameter) is any value passed into a batch script: C:> MyScript.cmd January 1234 "Some value" Arguments can also be passed to a subroutine with CALL: CALL :my_sub 2468. You can get the value of any argument using a % followed by it's numerical position on the command line.
I suspect the problem is that you've put the "-D" after the -jar
. Try this:
java -Dtest="true" -jar myApplication.jar
From the command line help:
java [-options] -jar jarfile [args...]
In other words, the way you've got it at the moment will treat -Dtest="true"
as one of the arguments to pass to main
instead of as a JVM argument.
(You should probably also drop the quotes, but it may well work anyway - it probably depends on your shell.)
That should be:
java -Dtest="true" -jar myApplication.jar
Then the following will return the value:
System.getProperty("test");
The value could be null
, though, so guard against an exception using a Boolean
:
boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );
Note that the getBoolean
method delegates the system property value, simplifying the code to:
if( Boolean.getBoolean( "test" ) ) {
// ...
}
You're giving parameters to your program instead to Java. Use
java -Dtest="true" -jar myApplication.jar
instead.
Consider using
"true".equalsIgnoreCase(System.getProperty("test"))
to avoid the NPE. But do not use "Yoda conditions" always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like
System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
is right (providing default true). A shorter possibility is
!"false".equalsIgnoreCase(System.getProperty("test"))
but not using double negation doesn't make it less hard to misunderstand.
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