How can I get the -D options passed to Java launch

I pass certain environment variables D as virtual machine parameters to a Java server application.

I need to get these variables from the application, but when I use System.getProperties (), I get all of them, as well as all the system properties defined at the operating system level that are not of interest to me.

Is there any way to open the -D options?

+5
source share
3 answers

You can get it using RuntimeMXBean (a management interface for the Java virtual machine runtime), like this

RuntimeMXBean bean = ManagementFactory.getRuntimeMXBean(); List<String> args = bean.getInputArguments(); 

Note that getInputArguments () Returns the input arguments passed to the Java virtual machine, which does not include the arguments in the main method. This method returns an empty list if there are no input arguments to the Java virtual machine.

+1
source

It is available in the RuntimeMXBean provided by the virtual machine. You can get a list of command line options by calling getInputArguments() ...

 import java.lang.management.ManagementFactory; public class CmdLine { public static void main(String... args) { System.out.println(ManagementFactory.getRuntimeMXBean().getInputArguments()); } } 
+1
source

Your best option is to use a special prefix for the properties you use so that you can distinguish them from others: java -Dfoo.bar=x -Dfoo.bat=y -Dfoo.baz=z ... and then:

 for(Map.Entry<String,String> kv: System.getProperties().entrySet()) { if(kv.getKey().starts with("foo")) { System.out.println("Command line property " + kv.getKey() + "=" + kv.getValue()); } } 
0
source

Source: https://habr.com/ru/post/1210427/


All Articles