简体   繁体   English

正确使用Java -D命令行参数

[英]Proper usage of Java -D command-line parameters

When passing a -D parameter in Java, what is the proper way of writing the command-line and then accessing it from code? 在Java中传递-D参数时,编写命令行然后从代码访问它的正确方法是什么?

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. 但是我收到一个NullPointerException。 What am I doing wrong? 我究竟做错了什么?

I suspect the problem is that you've put the "-D" after the -jar . 我怀疑的问题是,你已经把“-D” -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. 换句话说,目前您将其获取的方式将-Dtest="true"视为传递给main的参数之一,而不是JVM参数。

(You should probably also drop the quotes, but it may well work anyway - it probably depends on your shell.) (您可能应该删除引号,但无论如何它都可以正常工作-它可能取决于您的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 : 不过,该值可以为null ,因此请使用Boolean防止出现异常:

boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );

Note that the getBoolean method delegates the system property value, simplifying the code to: 请注意, getBoolean方法委派系统属性值,从而将代码简化为:

if( Boolean.getBoolean( "test" ) ) {
   // ...
}

You're giving parameters to your program instead to Java. 您正在为程序而不是Java提供参数。 Use 使用

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

instead. 代替。

Consider using 考虑使用

"true".equalsIgnoreCase(System.getProperty("test"))

to avoid the NPE. 避免NPE。 But do not use " Yoda conditions " always without thinking, sometimes throwing the NPE is the right behavior and sometimes something like 但是不要总是不加思索地使用“ 尤达条件 ”,有时扔NPE是正确的行为,有时

System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")

is right (providing default true). 是正确的(提供默认true)。 A shorter possibility is 可能性较小

!"false".equalsIgnoreCase(System.getProperty("test"))

but not using double negation doesn't make it less hard to misunderstand. 但不使用双重否定并不会使人们容易误解。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM