---
title: "[java] change the env in java code"
author: "feikiss"
date: "2013-05-30T17:04:54Z"
tags: ["Java", "setenv"]
categories: ["编程语言"]
slug: "java-change-the-env-in-java-code"
draft: false
lastmod: "2013-05-30T17:04:54Z"
id: 1880138
url: "https://feikiss.iteye.com/blog/1880138"
---

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:


```java

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.