`
feikiss
  • 浏览: 97961 次
  • 性别: Icon_minigender_1
  • 来自: 西安
社区版块
存档分类
最新评论

[java] change the env in java code

阅读更多
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
0
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics