Skip to main content

How do I set environment variables from Java?


How do I set environment variables from Java? I see that I can do this for subprocesses using ProcessBuilder. I have several subprocesses to start, though, so I'd rather modify the current process's environment and let the subprocesses inherit it.



There's a System.getenv(String) for getting a single environment variable. I can also get a Map of the complete set of environment variables with System.getenv(). But calling put() on that Map throws an UnsupportedOperationException -- apparently they mean for the environment to be read only. And there's no System.setenv().



So, is there any way to set environment variables in the currently running process? If so, how? If not, what's the rationale? (Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?) And if not, any good suggestions for managing the environment variable changes that I'm going to need to be feeding to several subprocesses?


Source: Tips4allCCNA FINAL EXAM

Comments

  1. (Is it because this is Java and therefore I shouldn't be doing evil nonportable obsolete things like touching my environment?)


    I think you've hit the nail on the head.

    A possible way to ease the burden would be to factor out a method

    void setUpEnvironment(ProcessBuilder builder) {
    Map<String, String> env = builder.environment();
    // blah blah
    }


    and pass any ProcessBuilders through it before starting them.

    Also, you probably already know this, but you can start more than one process with the same ProcessBuilder. So if your subprocesses are the same, you don't need to do this setup over and over.

    ReplyDelete
  2. public static void set(Map<String, String> newenv) throws Exception {
    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);
    }
    }
    }

    ReplyDelete
  3. I found that a combination of the two dirty hacks above works best, as one of the does not work under linux, one does not work under windows 7. So to get a multiplatform evil hack I combined them:

    protected 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();
    }
    }


    Works like a charm. Full credits to the two authors of these hacks.

    ReplyDelete
  4. // this is a dirty hack - but should be ok for a unittest.
    private void setNewEnvironmentHack(Map<String, String> newenv) throws Exception
    {
    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.clear();
    env.putAll(newenv);
    Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
    theCaseInsensitiveEnvironmentField.setAccessible(true);
    Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
    cienv.clear();
    cienv.putAll(newenv);
    }

    ReplyDelete
  5. Poking around online, it looks like it might be possible to do this with JNI. You'd then have to make a call to putenv() from C, and you'd (presumably) have to do it in a way that worked on both Windows and UNIX.

    If all that can be done, it surely wouldn't be too hard for Java itself to support this instead of putting me in a straight jacket.

    A Perl-speaking friend elsewhere suggests that this is because environment variables are process global and Java is striving for good isolation for good design.

    ReplyDelete
  6. You can pass parameters into your initial java process with -D:

    java -cp <classpath> -Dkey1=value -Dkey2=value ...

    ReplyDelete

Post a Comment

Popular posts from this blog

Wildcards in a hosts file

I want to setup my local development machine so that any requests for *.local are redirected to localhost . The idea is that as I develop multiple sites, I can just add vhosts to Apache called site1.local , site2.local etc, and have them all resolve to localhost , while Apache serves a different site accordingly.