Tuesday, April 24, 2018

Set/unset environment variables from the JVM (Groovy)


Dirty hack recommended only for testing. Only ever tested in Linux; may not work at all on Windows.

 
def setEnv(String key, String value) {
    try {
        // Dirty hack to set environment variables from JVM
        // Only tested in Linux - may not work in Windows at all
        Map<String, String> env = System.getenv()
        Class<?> cl = env.getClass()
        Field field = cl.getDeclaredField("m")
        field.setAccessible(true)
        Map<String, String> writableEnv = (Map<String, String>) field.get(env)
        writableEnv.put(key, value)
    } catch (Exception e) {
        throw new IllegalStateException("Failed to set environment variable", e)
    }
}

def unsetEnv(String key) {
    try {
        // Dirty hack to unset environment variables from JVM
        // Only tested in Linux - may not work in Windows at all
        Map<String, String> env = System.getenv()
        Class<?> cl = env.getClass()
        Field field = cl.getDeclaredField("m")
        field.setAccessible(true)
        Map<String, String> writableEnv = (Map<String, String>) field.get(env)
        writableEnv.remove(key)
    } catch (Exception e) {
        throw new IllegalStateException("Failed to set environment variable", e)
    }
}