How to Change Environment Variables in Java [Snippet]

Datetime:2017-04-20 05:30:50         Topic: Java          Share        Original >>
Here to See The Original Article!!!

How to Change Environment Variables in Java [Snippet]

DZone's Guide to

How to Change Environment Variables in Java [Snippet]

Looking for a quick, dirty way to change environment variables in Java? Here's how to do it, but it relies on the JDK's internals, so be careful — it's really dirty!

Free Resource

Join the DZone community and get the full member experience.

What every Java engineer should know about microservices: Reactive Microservices Architecture .  Brought to you in partnership with Lightbend .

And the second dirty hack for the day: How to change system environment variables in Java — at least during the lifetime of a JVM.

This can be useful when testing functionality that accesses environment variables set by container runtimes like Docker.

public class EnvironmentsTest {

    public void testGetFoobar() throws Exception {

        injectEnvironmentVariable("FOOBAR_ENV", "Foo");

        assertThat(System.getenv("FOOBAR_ENV"), is("Foo"));

    private static void injectEnvironmentVariable(String key, String value)
            throws Exception {

        Class<?> processEnvironment = Class.forName("java.lang.ProcessEnvironment");

        Field unmodifiableMapField = getAccessibleField(processEnvironment, "theUnmodifiableEnvironment");
        Object unmodifiableMap = unmodifiableMapField.get(null);
        injectIntoUnmodifiableMap(key, value, unmodifiableMap);

        Field mapField = getAccessibleField(processEnvironment, "theEnvironment");
        Map<String, String> map = (Map<String, String>) mapField.get(null);
        map.put(key, value);

    private static Field getAccessibleField(Class<?> clazz, String fieldName)
            throws NoSuchFieldException {

        Field field = clazz.getDeclaredField(fieldName);
        return field;

    private static void injectIntoUnmodifiableMap(String key, String value, Object map)
            throws ReflectiveOperationException {

        Class unmodifiableMap = Class.forName("java.util.Collections$UnmodifiableMap");
        Field field = getAccessibleField(unmodifiableMap, "m");
        Object obj = field.get(map);
        ((Map<String, String>) obj).put(key, value);

This is a very dirty hack, that relies on the internals of the JDK, so please use it with care and, of course, only in testing scenarios. Also, this solution only works in more recent versions of JDK 1.8 — before that, the internal maps were split up and named differently.

You may want to consider changing your code to insert another abstraction for the environment setting — to make the configuration changeable.

Microservices for Java, explained. Revitalize your legacy systems (and your career) with Reactive Microservices Architecture , a free O'Reilly book. Brought to you in partnership with Lightbend .