[英]Setting environment variable in Java 8
我有与此类似的代码(更新环境变量):
private static void setEnv(Map<String, String> envs) {
try {
Class<?> pec = Class.forName("java.lang.ProcessEnvironment");
Field tef = pec.getDeclaredField("theEnvironment");
tef.setAccessible(true);
Map<String, String> env = (Map<String, String>) tef.get(null);
env.clear();
env.putAll(envs);
Field tcief = pec.getDeclaredField("theCaseInsensitiveEnvironment");
tcief.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) tcief.get(null);
cienv.clear();
cienv.putAll(envs);
} catch (Exception e) {
logger.printStackTrace(e);
}
}
我已经为此代码编写了一些单元测试,现在我正在 Java 8 (1.8.0) 上进行测试。 此代码不适用于在 JUnit 中Run
,但在作为Debug
运行时有效(带断点和不带断点)。 不起作用意味着我得到这样的环境变量(PATH)
String path = System.getenv("PATH");
我看到没有我的路径( c:\\\\temp
)。 在 Java 7 (1.7.0_51) 上测试工作正常,所有 Java 都是 32 位的,我没有使用额外的线程。 你有什么想法如何解决这个问题吗?
问题在于区分大小写的键。 参数envs
被创建为
Map<String, String> envs = new HashMap<String, String>();
但将其创建为
Map<String, String> envs = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
解决了这个问题。 我得到了不同的结果env["Path"]
, env["PATH"]
等等。
您也可以使用 System Stubs 实现此目的 - https://github.com/webcompere/system-stubs
Map<String, String> someMap = ...; // work out the env variables
EnvironmentVariables environmentVariables = new EnvironmentVariables(someMap);
当对象处于活动状态时,环境变量将应用于环境。 这是通过它的 JUnit 4 或 5 插件实现的,或者通过使用对象上的execute
方法来包装可执行代码来实现。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.