ITeye博客

[java] change the env in java code

feikiss · 2013-05-30 17:04 · java知识 · 英语学习 · 编程语言 · Java · setenv · Markdown

In Java API, there is the method System.getenv(), but no interface to set the env. This is because Java forbid the operation based on platform. But sometimes we need to change the env to finish some unit test. The following way just like a hack but it is ok to unit test:


private void setNewEnvironmentHack(Map<String, String> newenv) throws Exception
	    {
	      Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
	      Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
	      theEnvironmentField.setAccessible(true);
	      Map<String, String> env = (Map<String, String>) theEnvironmentField.get(null);
	      env.clear();
	      env.putAll(newenv);
	      Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
	      theCaseInsensitiveEnvironmentField.setAccessible(true);
	      Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
	      cienv.clear();
	      cienv.putAll(newenv);
	    }

The following implemented code comes from the stackoverflow, record it here in case we may need it again.

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。