1

This is similar to a pretty basic question, I'm trying to find a list of system properties passed to the java program from the command line only. E.g., running

java -Dsome.property=value -Dother.property=value2

I'm trying to get a list of JUST these properties. Ignore the specific property names in the example, the actual command line arguments will be arbitrarily named so it is not feasible to explicitly call System.getProperty("some.property") for each property I need.

System.getProperties() returns many properties that I do not have any interest in. Is it possible to differentiate between properties set on the command line when starting the program vs those that come from elsewhere?

Daniel
  • 3,312
  • 1
  • 14
  • 31
Trebla
  • 1,164
  • 1
  • 13
  • 28

2 Answers2

3

Is it possible to differentiate between properties set on the command line when starting the program vs those that come from elsewhere?

As far as I know, this is not supported. By the time your code is executing, the command line system properties have already been munged with all of the others.

Depending on what you are really trying to accomplish, one thing to consider might be to not set them as command line system properties but instead pass them as parameters to your program so you can evaluate them and then set them as system properties in your main method before much of your other code executes.

I hope that helps.

Jeff Scott Brown
  • 26,804
  • 2
  • 30
  • 47
  • It does. I did work around it as you suggest, but was still curious if it was possible. Good to know it's not. – Trebla Mar 28 '19 at 18:41
0

You can introspect JVM itself:

How to get VM arguments from inside of Java application?

import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
...
RuntimeMXBean runtimeMxBean = ManagementFactory.getRuntimeMXBean();
List<String> arguments = runtimeMxBean.getInputArguments();

Search for -D options. I don't recommend this solution, the API is for logging/monitoring/debugging. Usage in business code is code smell.

gavenkoa
  • 45,285
  • 19
  • 251
  • 303