简体   繁体   English

如何通过系统属性将数组或值列表传递给Java-以及如何访问它?

[英]How do I pass an array or list of values to Java via system properties - and how do I access it?

Is there a way to pass a list of values into Java, using only one system property? 有没有一种方法可以仅使用一个系统属性将值列表传递给Java?

I'm thinking of something along the lines -DMY_LIST=val1,val2,val3 or -DMY_LIST={val1, val2} 我正在考虑-DMY_LIST=val1,val2,val3-DMY_LIST={val1, val2}

Any ideas? 有任何想法吗?

How would I access that in Java? 我将如何在Java中访问它?

Update: I initially asked for environment variables, but actually meant system properties. 更新:我最初询问环境变量,但实际上是系统属性。 Similar principle, but quite different... I changed title and text accordingly now. 原理相似,但有很大不同...我现在相应地更改了标题和文本。 Thanks, @serge-ballesta 谢谢@ serge-ballesta

From Oracle Javase tutorial On the Java platform, an application uses System.getenv to retrieve environment variable values. 来自Oracle Javase教程 在Java平台上,应用程序使用System.getenv检索环境变量值。 Without an argument, getenv returns a read-only instance of java.util.Map, where the map keys are the environment variable names, and the map values are the environment variable values. 没有参数,getenv返回java.util.Map的只读实例,其中映射键是环境变量名称,而映射值是环境变量值。

So if you have an environment variable MY_LIST=val1,val2,val3 , you can use it as simple as 因此,如果您有一个环境变量MY_LIST=val1,val2,val3 ,则可以像使用它一样简单

String strlist = System.getenv().get("MY_LIST");
List<String> list = Arrays.asList(strlist.split(","));

Edit: fixed call of getenv (forgot parentheses - thanks to Christian) 编辑:修复getenv的调用(忘了括号-感谢Christian)

I must precise that my anwer concerns environment variable which is the title of the post. 我必须弄清楚,我的回答与环境变量有关 ,这是该职位的标题。 But java -D MY_LIST=a,b,c ... sets system properties and it in not the same. 但是java -D MY_LIST=a,b,c ...设置系统属性,并且系统属性 并不相同。 To access system properties set by -D option, I should write instead : 要访问由-D选项设置的系统属性,我应该写:

String strlist = System.getProperty("MY_LIST");
List<String> list = Arrays.asList(strlist.split(","));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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