0

Wondering what happens when I declare a custom property in java using -D command. I came to know that other system properties are not stored, instead generated by JVM. So what will happen to the property that I created? Can I use it next time while I compile the code without declaring again?

example: java -D"custom_key"="custom_value" some_class

sepp2k
  • 363,768
  • 54
  • 674
  • 675

1 Answers1

1

System properties are evaluated at runtime only not at compilation time.

public class SysProp {
  public static void main(String[] args) {
    System.out.println(System.getProperty("foo", "<foo not set>"));
  }
}

java SysProp

Output: <foo not set>

java -Dfoo=bar

Output: bar

vanje
  • 10,180
  • 2
  • 31
  • 47
  • Got it. Can I reuse the custom property? – Kartik Hegde Aug 24 '22 at 06:03
  • 1
    @KartikHegde what is “reuse the custom property” supposed to mean? – Holger Aug 24 '22 at 06:58
  • I second Holger. I don't know what "reuse the custom property" could mean in this context. You set it when you start the program to have some kind of control over the behaviour. Usually for some cross-sectional concerns (e.g. which XML parser implementation to use or proxy server address for HTTP request, etc.). Otherwise, you would use a regular command line parameter. – vanje Aug 24 '22 at 08:32
  • By reuse I meant the next time I execute the program should I set it again? – Kartik Hegde Aug 24 '22 at 10:02
  • Yes, you should set it each time you start your program. Usually, you create a starting shell script or batch file where all the options are set. – vanje Aug 24 '22 at 12:00
  • 2
    @KartikHegde it seems that you are assuming features (like persistence) for system properties that do not exist. This is just an ordinary map from string keys to string values. Some of them are automatically added by the JVM at startup, but that’s the only special thing. You can add key value pairs at startup via `-D` option or just call `System.setProperty(…)` at any time. Like with any other runtime object, the contents of that map is gone when the JVM terminates. – Holger Aug 25 '22 at 08:05