Proper usage of Java -D command-line parameters

后端 未结 3 1009
星月不相逢
星月不相逢 2020-11-29 16:33

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

3条回答
  •  猫巷女王i
    2020-11-29 17:15

    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.

提交回复
热议问题