문제

If I specify a system property multiple times when invoking the JVM which value will I actually get when I retrieve the property? e.g.

java -Dprop=A -Dprop=B -jar my.jar

What will be the result when I call System.getProperty("prop");?

The Java documentation on this does not really tell me anything useful on this front.

In my non-scientific testing on a couple of machines running different JVMs it seems like the last value is the one returned (which is actually the behavior I need) but I wondered if this behavior is actually defined officially anywhere or can it vary between JVMs?

도움이 되었습니까?

해결책

The java.util.System class is backed by a Properties class, which is just an extension of Hashtable. Assuming the values are read in order when passing as arguments to the JVM, then the last value assigned will be the final value.

다른 팁

There's nothing like writing a little class to see how it works.

public class PropTest {

  public static void main(String[] args) {
    System.out.println(System.getProperty("prop"));
  }

}

Which when compiled and ran with the command line

java -Dprop=A -Dprop=B -Dprop=C PropTest

yeilds the output

C

Which would imply that the values are put into the table left to right, with the last value overwriting previous values.

Just to make a note of the environment, Fedora 16, Linux 3.3.7, 64 bit

> java -version

java version "1.6.0_24"
OpenJDK Runtime Environment (IcedTea6 1.11.1) (fedora-65.1.11.1.fc16-x86_64)
OpenJDK 64-Bit Server VM (build 20.0-b12, mixed mode)

I'm not sure if there's anything documented for Oracle.

According to IBM JRE documents:

The sequence of the Java options on the command line defines which options take precedence during startup. Rightmost options have precedence over leftmost options.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top