![](/img/trans.png)
[英]Split a string containing command-line parameters into a String[] in Java
[英]Proper usage of Java -D command-line parameters
在Java中传递-D参数时,编写命令行然后从代码访问它的正确方法是什么?
例如,我尝试编写类似这样的内容...
if (System.getProperty("test").equalsIgnoreCase("true"))
{
//Do something
}
然后这样称呼它...
java -jar myApplication.jar -Dtest="true"
但是我收到一个NullPointerException。 我究竟做错了什么?
我怀疑的问题是,你已经把“-D” 后 -jar
。 尝试这个:
java -Dtest="true" -jar myApplication.jar
从命令行帮助:
java [-options] -jar jarfile [args...]
换句话说,目前您将其获取的方式将-Dtest="true"
视为传递给main
的参数之一,而不是JVM参数。
(您可能还应该删除引号,但无论如何它都可以正常工作-它可能取决于您的shell。)
应该是:
java -Dtest="true" -jar myApplication.jar
然后以下将返回值:
System.getProperty("test");
不过,该值可以为null
,因此请使用Boolean
防止出现异常:
boolean b = Boolean.parseBoolean( System.getProperty( "test" ) );
请注意, getBoolean
方法委派系统属性值,从而将代码简化为:
if( Boolean.getBoolean( "test" ) ) {
// ...
}
您正在为程序而不是Java提供参数。 使用
java -Dtest="true" -jar myApplication.jar
代替。
考虑使用
"true".equalsIgnoreCase(System.getProperty("test"))
避免NPE。 但是不要总是不加思索地使用“ 尤达条件 ”,有时扔NPE是正确的行为,有时
System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true")
是正确的(提供默认true)。 可能性较小
!"false".equalsIgnoreCase(System.getProperty("test"))
但不使用双重否定并不会使人们容易误解。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.