正确使用Java -D命令行参数
在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来防止exception: 
 boolean b = Boolean.parseBoolean( System.getProperty( "test" ) ); 
 请注意, getBoolean方法委托系统属性值,将代码简化为: 
 if( Boolean.getBoolean( "test" ) ) { // ... } 
您将parameter passing给您的程序,而不是Java。 使用
 java -Dtest="true" -jar myApplication.jar 
代替。
考虑使用
 "true".equalsIgnoreCase(System.getProperty("test")) 
避免NPE。 但不要总是用“ 尤达条件 ”来思考,有时候抛出NPE是正确的行为,有时候也是这样的
 System.getProperty("test") == null || System.getProperty("test").equalsIgnoreCase("true") 
是正确的(提供默认值)。 更短的可能性是
 !"false".equalsIgnoreCase(System.getProperty("test")) 
但不使用双重否定不会使人难以理解。