vinnygray
vinnygray

Reputation: 171

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?

Upvotes: 5

Views: 1035

Answers (3)

Dima
Dima

Reputation: 40510

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());
    }
}

Upvotes: 0

sol4me
sol4me

Reputation: 15708

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.

Upvotes: 3

Todd
Todd

Reputation: 31710

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());
    }
}

Upvotes: 1

Related Questions