Created
June 9, 2015 03:37
-
-
Save zhaopengme/53719298b6edf1a99a41 to your computer and use it in GitHub Desktop.
set environment variables from Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.lang.reflect.Field; | |
import java.util.Collections; | |
import java.util.Map; | |
/** | |
* Created by mikey.zhaopeng on 2015/6/9. | |
*/ | |
public class EnvUtil { | |
public static void setEnv(Map<String, String> newenv) { | |
try { | |
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.putAll(newenv); | |
Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment"); | |
theCaseInsensitiveEnvironmentField.setAccessible(true); | |
Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null); | |
cienv.putAll(newenv); | |
} catch (NoSuchFieldException e) { | |
try { | |
Class[] classes = Collections.class.getDeclaredClasses(); | |
Map<String, String> env = System.getenv(); | |
for (Class cl : classes) { | |
if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) { | |
Field field = cl.getDeclaredField("m"); | |
field.setAccessible(true); | |
Object obj = field.get(env); | |
Map<String, String> map = (Map<String, String>) obj; | |
map.clear(); | |
map.putAll(newenv); | |
} | |
} | |
} catch (Exception e2) { | |
e2.printStackTrace(); | |
} | |
} catch (Exception e1) { | |
e1.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment