简体   繁体   中英

How can I obtain the -D parameters passed in to Java launch

I am passing in certain -D environment variables as VM options to a Java server application.

I need to retrieve those variables from the application, but when I use System.getProperties() I am getting all of those, plus all of the system properties defined at the operating system level, which I am not interested in.

Is there any way to just discover the -D parameters?

This is available in the RuntimeMXBean provided by the VM. You can get a List of command-line parameters through the getInputArguments() call...

import java.lang.management.ManagementFactory;

public class CmdLine {
    public static void main(String... args) {
        System.out.println(ManagementFactory.getRuntimeMXBean().getInputArguments());
    }
}

You can obtain it using RuntimeMXBean (The management interface for the runtime system of the Java virtual machine) like this

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

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

Your best option is to use a special prefix for the properties you are using, so that you can distinguish them from others: java -Dfoo.bar=x -Dfoo.bat=y -Dfoo.baz=z ... , 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());
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM