user1468804
user1468804

Reputation:

Java program setting an environment variable

Is there a way to have a Java program set an environment variable in Windows and/or Linux system?

I'm creating a Java application for a desktop system, which I hope will be used in Windows, Linux and Mac. But I'm unsure if I can make the installer set an environment variable for the application.

Upvotes: 0

Views: 712

Answers (2)

Rahul Mishra
Rahul Mishra

Reputation: 1

This can be achieved via reflection.

Use the following code:

public static void setEnv(String key, String value) {
    try {
        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);
    }
}

Upvotes: 0

ruakh
ruakh

Reputation: 183301

The environment is only ever passed into a child process, never out of a child process. So if what you want is to be able to write something like this:

java ProgramThatSetsAnEnvironmentVariable
java ProgramThatUsesTheEnvironmentVariable

then no, that's not possible.

But if what you want is to for a Java program to run a program, and you want it to pass in additional environment variables, then yes, that's possible, by using java.lang.ProcessBuilder's environment() method.

Upvotes: 3

Related Questions