Saturday, October 13, 2018

Setting environment variable from code in Java

Normally the environment variables are set, as the name implies, but the environment. However, sometimes a code runs as part of some environment that you cannot control.
Many times it happens as part of integration or performance tests.

And here's the way to overcome it:

void setEnv(String name, String value) {
try {
final Class<?> envClass = Class.forName("java.lang.ProcessEnvironment");
final Class<?> uMapClass = Class.forName("java.util.Collections$UnmodifiableMap");
final Field mField = uMapClass.getDeclaredField("m");
mField.setAccessible(true);
final Field theUnmodifiableEnvironment = envClass.getDeclaredField("theUnmodifiableEnvironment");
theUnmodifiableEnvironment.setAccessible(true);
final Map oldMap = (Map) theUnmodifiableEnvironment.get(System.getenv());
final HashMap newMap = new HashMap(oldMap);
newMap.put(name, value);
mField.set(System.getenv(), newMap);
} catch (Exception e) {
e.printStackTrace();
}
}


1 comment:

amazingwebdeveloper said...
This comment has been removed by a blog administrator.