Proper usage of Java -D command-line parameters

后端 未结 3 1014
星月不相逢
星月不相逢 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条回答
  •  广开言路
    2020-11-29 17:17

    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:

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

    Note that the getBoolean method delegates the system property value, simplifying the code to:

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

提交回复
热议问题