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

Slow Android emulator

I have a 2.67 GHz Celeron processor, 1.21 GB of RAM on a x86 Windows XP Professional machine. My understanding is that the Android emulator should start fairly quickly on such a machine, but for me it does not. I have followed all instructions in setting up the IDE, SDKs, JDKs and such and have had some success in staring the emulator quickly but is very particulary. How can I, if possible, fix this problem?

CCNA 3 Final Exam => latest version

1 . Which security protocol or measure would provide the greatest protection for a wireless LAN? WPA2 cloaking SSIDs shared WEP key MAC address filtering   2 . Refer to the exhibit. All trunk links are operational and all VLANs are allowed on all trunk links. An ARP request is sent by computer 5. Which device or devices will receive this message? only computer 4 computer 3 and RTR-A computer 4 and RTR-A computer 1, computer 2, computer 4, and RTR-A computer 1, computer 2, computer 3, computer 4, and RTR-A all of the computers and the router   3 . Refer to the exhibit. Hosts A and B, connected to hub HB1, attempt to transmit a frame at the same time but a collision occurs. Which hosts will receive the collision jamming signal? only hosts A and B only hosts A, B, and C only hosts A, B, C, and D only hosts A, B, C, and E   4 . Refer to the exhibit. Router RA receives a packet with a source address of 192.168.1.65 and a destination address of 192.168.1.161...