Proper usage of Java -D command-line parameters

Ryan Berger picture Ryan Berger · Feb 18, 2011 · Viewed 194.2k times · Source

When passing a -D parameter in Java, what is the proper way of writing the command-line and then accessing it from code?

For example, I have tried writing something like this...

if (System.getProperty("test").equalsIgnoreCase("true"))
{
   //Do something
}

And then calling it like this...

java -jar myApplication.jar -Dtest="true"

But I receive a NullPointerException. What am I doing wrong?

Answer

Jon Skeet picture Jon Skeet · Feb 18, 2011

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