Is it possible to set an environment variable at runtime from a Java application? In Java 1.5 java.lang.System class there is the getenv() method, I would only need a setenv
You can get a handle on the underlying map that java.lang.ProcessEnvironment is holding on to, and then put new stuff and remove stuff all you want.
This works on java 1.8.0_144. Can't guarantee it works on any other version of java, but it's probably similar if you really need to change the environment at run time.
private static Map getModifiableEnvironment() throws Exception{
Class pe = Class.forName("java.lang.ProcessEnvironment");
Method getenv = pe.getDeclaredMethod("getenv");
getenv.setAccessible(true);
Object unmodifiableEnvironment = getenv.invoke(null);
Class map = Class.forName("java.util.Collections$UnmodifiableMap");
Field m = map.getDeclaredField("m");
m.setAccessible(true);
return (Map) m.get(unmodifiableEnvironment);
}
After you get the reference to the map, just add whatever you want and you can now retrieve it using the regular old System.getenv("") call.
I tried this its working in MAC not working in Windows in both os java version 1.8_161