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

Why is this Javascript much *slower* than its jQuery equivalent?

I have a HTML list of about 500 items and a "filter" box above it. I started by using jQuery to filter the list when I typed a letter (timing code added later): $('#filter').keyup( function() { var jqStart = (new Date).getTime(); var search = $(this).val().toLowerCase(); var $list = $('ul.ablist > li'); $list.each( function() { if ( $(this).text().toLowerCase().indexOf(search) === -1 ) $(this).hide(); else $(this).show(); } ); console.log('Time: ' + ((new Date).getTime() - jqStart)); } ); However, there was a couple of seconds delay after typing each letter (particularly the first letter). So I thought it may be slightly quicker if I used plain Javascript (I read recently that jQuery's each function is particularly slow). Here's my JS equivalent: document.getElementById('filter').addEventListener( 'keyup', function () { var jsStart = (new Date).getTime()...

Is it possible to have IF statement in an Echo statement in PHP

Thanks in advance. I did look at the other questions/answers that were similar and didn't find exactly what I was looking for. I'm trying to do this, am I on the right path? echo " <div id='tabs-".$match."'> <textarea id='".$match."' name='".$match."'>". if ($COLUMN_NAME === $match) { echo $FIELD_WITH_COLUMN_NAME; } else { } ."</textarea> <script type='text/javascript'> CKEDITOR.replace( '".$match."' ); </script> </div>"; I am getting the following error message in the browser: Parse error: syntax error, unexpected T_IF Please let me know if this is the right way to go about nesting an IF statement inside an echo. Thank you.