[java] change the env in java code,
分享于 点击 10046 次 点评:88
[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.
相关文章
- 暂无相关文章
用户点评