如何从Java中设置环境变量?我发现我可以使用ProcessBuilder为子流程做到这一点。不过,我有几个子流程要启动,所以我宁愿修改当前流程的环境,让子流程继承它。

有一个System.getenv(String)用于获取单个环境变量。我还可以使用System.getenv()获得完整环境变量集的Map。但是,在该Map上调用put()会抛出UnsupportedOperationException——显然,它们意味着环境是只读的。并且,没有System.setenv()。

那么,有没有办法在当前运行的进程中设置环境变量呢?如果有,怎么做?如果不是,理由是什么?(是不是因为这是Java,所以我不应该做邪恶的、不可移植的、过时的事情,比如触摸我的环境?)如果不是,有什么好的建议来管理我将需要提供给几个子流程的环境变量更改吗?


当前回答

像大多数找到这个线程的人一样,我正在编写一些单元测试,需要修改环境变量以设置测试运行的正确条件。然而,我发现被点赞最多的答案有一些问题和/或非常神秘或过于复杂。希望这能帮助其他人更快地找到解决方案。

首先,我终于发现@Hubert Grzeskowiak的解决方案是最简单的,对我来说很管用。我希望我能先讲到这一点。它基于@Edward Campbell的回答,但是没有复杂的for循环搜索。

然而,我从@pushy的解决方案开始,它得到了最多的赞。它是@anonymous和@Edward Campbell's的组合。@pushy声称这两种方法都需要覆盖Linux和Windows环境。我在OS X下运行,发现两者都可以工作(一旦@匿名方法的问题被修复)。正如其他人所指出的,这种解决方案在大多数情况下都有效,但并非所有情况都有效。

I think the source of most of the confusion comes from @anonymous's solution operating on the 'theEnvironment' field. Looking at the definition of the ProcessEnvironment structure, 'theEnvironment' is not a Map< String, String > but rather it is a Map< Variable, Value >. Clearing the map works fine, but the putAll operation rebuilds the map a Map< String, String >, which potentially causes problems when subsequent operations operate on the data structure using the normal API that expects Map< Variable, Value >. Also, accessing/removing individual elements is a problem. The solution is to access 'theEnvironment' indirectly through 'theUnmodifiableEnvironment'. But since this is a type UnmodifiableMap the access must be done through the private variable 'm' of the UnmodifiableMap type. See getModifiableEnvironmentMap2 in code below.

在我的例子中,我需要为我的测试删除一些环境变量(其他的应该保持不变)。然后,我想在测试之后将环境变量恢复到它们之前的状态。下面的例程会让你更容易做到。我在OS X上测试了两个版本的getModifiableEnvironmentMap,两者的工作效果相当。尽管基于本线程中的注释,但根据环境的不同,其中一种可能比另一种更好。

注意:我没有包括对' casaseinsensitiveenvironmentfield '的访问,因为这似乎是Windows特定的,我没有办法测试它,但添加它应该是直截了当地。

private Map<String, String> getModifiableEnvironmentMap() {
    try {
        Map<String,String> unmodifiableEnv = System.getenv();
        Class<?> cl = unmodifiableEnv.getClass();
        Field field = cl.getDeclaredField("m");
        field.setAccessible(true);
        Map<String,String> modifiableEnv = (Map<String,String>) field.get(unmodifiableEnv);
        return modifiableEnv;
    } catch(Exception e) {
        throw new RuntimeException("Unable to access writable environment variable map.");
    }
}

private Map<String, String> getModifiableEnvironmentMap2() {
    try {
        Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        Field theUnmodifiableEnvironmentField = processEnvironmentClass.getDeclaredField("theUnmodifiableEnvironment");
        theUnmodifiableEnvironmentField.setAccessible(true);
        Map<String,String> theUnmodifiableEnvironment = (Map<String,String>)theUnmodifiableEnvironmentField.get(null);

        Class<?> theUnmodifiableEnvironmentClass = theUnmodifiableEnvironment.getClass();
        Field theModifiableEnvField = theUnmodifiableEnvironmentClass.getDeclaredField("m");
        theModifiableEnvField.setAccessible(true);
        Map<String,String> modifiableEnv = (Map<String,String>) theModifiableEnvField.get(theUnmodifiableEnvironment);
        return modifiableEnv;
    } catch(Exception e) {
        throw new RuntimeException("Unable to access writable environment variable map.");
    }
}

private Map<String, String> clearEnvironmentVars(String[] keys) {

    Map<String,String> modifiableEnv = getModifiableEnvironmentMap();

    HashMap<String, String> savedVals = new HashMap<String, String>();

    for(String k : keys) {
        String val = modifiableEnv.remove(k);
        if (val != null) { savedVals.put(k, val); }
    }
    return savedVals;
}

private void setEnvironmentVars(Map<String, String> varMap) {
    getModifiableEnvironmentMap().putAll(varMap);   
}

@Test
public void myTest() {
    String[] keys = { "key1", "key2", "key3" };
    Map<String, String> savedVars = clearEnvironmentVars(keys);

    // do test

    setEnvironmentVars(savedVars);
}

其他回答

如果您像我一样在测试中遇到这个问题,并且正在使用Junit5,那么Junit-pioneer提供了非常有用的注释。maven版本

例子:

@Test
@SetEnvironmentVariable(key = "some variable",value = "new value")
void test() {
    assertThat(System.getenv("some variable")).
        isEqualTo("new value");
}

怎么推荐都不为过。

像大多数找到这个线程的人一样,我正在编写一些单元测试,需要修改环境变量以设置测试运行的正确条件。然而,我发现被点赞最多的答案有一些问题和/或非常神秘或过于复杂。希望这能帮助其他人更快地找到解决方案。

首先,我终于发现@Hubert Grzeskowiak的解决方案是最简单的,对我来说很管用。我希望我能先讲到这一点。它基于@Edward Campbell的回答,但是没有复杂的for循环搜索。

然而,我从@pushy的解决方案开始,它得到了最多的赞。它是@anonymous和@Edward Campbell's的组合。@pushy声称这两种方法都需要覆盖Linux和Windows环境。我在OS X下运行,发现两者都可以工作(一旦@匿名方法的问题被修复)。正如其他人所指出的,这种解决方案在大多数情况下都有效,但并非所有情况都有效。

I think the source of most of the confusion comes from @anonymous's solution operating on the 'theEnvironment' field. Looking at the definition of the ProcessEnvironment structure, 'theEnvironment' is not a Map< String, String > but rather it is a Map< Variable, Value >. Clearing the map works fine, but the putAll operation rebuilds the map a Map< String, String >, which potentially causes problems when subsequent operations operate on the data structure using the normal API that expects Map< Variable, Value >. Also, accessing/removing individual elements is a problem. The solution is to access 'theEnvironment' indirectly through 'theUnmodifiableEnvironment'. But since this is a type UnmodifiableMap the access must be done through the private variable 'm' of the UnmodifiableMap type. See getModifiableEnvironmentMap2 in code below.

在我的例子中,我需要为我的测试删除一些环境变量(其他的应该保持不变)。然后,我想在测试之后将环境变量恢复到它们之前的状态。下面的例程会让你更容易做到。我在OS X上测试了两个版本的getModifiableEnvironmentMap,两者的工作效果相当。尽管基于本线程中的注释,但根据环境的不同,其中一种可能比另一种更好。

注意:我没有包括对' casaseinsensitiveenvironmentfield '的访问,因为这似乎是Windows特定的,我没有办法测试它,但添加它应该是直截了当地。

private Map<String, String> getModifiableEnvironmentMap() {
    try {
        Map<String,String> unmodifiableEnv = System.getenv();
        Class<?> cl = unmodifiableEnv.getClass();
        Field field = cl.getDeclaredField("m");
        field.setAccessible(true);
        Map<String,String> modifiableEnv = (Map<String,String>) field.get(unmodifiableEnv);
        return modifiableEnv;
    } catch(Exception e) {
        throw new RuntimeException("Unable to access writable environment variable map.");
    }
}

private Map<String, String> getModifiableEnvironmentMap2() {
    try {
        Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
        Field theUnmodifiableEnvironmentField = processEnvironmentClass.getDeclaredField("theUnmodifiableEnvironment");
        theUnmodifiableEnvironmentField.setAccessible(true);
        Map<String,String> theUnmodifiableEnvironment = (Map<String,String>)theUnmodifiableEnvironmentField.get(null);

        Class<?> theUnmodifiableEnvironmentClass = theUnmodifiableEnvironment.getClass();
        Field theModifiableEnvField = theUnmodifiableEnvironmentClass.getDeclaredField("m");
        theModifiableEnvField.setAccessible(true);
        Map<String,String> modifiableEnv = (Map<String,String>) theModifiableEnvField.get(theUnmodifiableEnvironment);
        return modifiableEnv;
    } catch(Exception e) {
        throw new RuntimeException("Unable to access writable environment variable map.");
    }
}

private Map<String, String> clearEnvironmentVars(String[] keys) {

    Map<String,String> modifiableEnv = getModifiableEnvironmentMap();

    HashMap<String, String> savedVals = new HashMap<String, String>();

    for(String k : keys) {
        String val = modifiableEnv.remove(k);
        if (val != null) { savedVals.put(k, val); }
    }
    return savedVals;
}

private void setEnvironmentVars(Map<String, String> varMap) {
    getModifiableEnvironmentMap().putAll(varMap);   
}

@Test
public void myTest() {
    String[] keys = { "key1", "key2", "key3" };
    Map<String, String> savedVars = clearEnvironmentVars(keys);

    // do test

    setEnvironmentVars(savedVars);
}

Kotlin中的一个版本,在这个算法中,我创建了一个装饰器,允许您从环境中设置和获取变量。

import java.util.Collections
import kotlin.reflect.KProperty
​
class EnvironmentDelegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        return System.getenv(property.name) ?: "-"
    }
​
    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        val key = property.name
​
        val classes: Array<Class<*>> = Collections::class.java.declaredClasses
        val env = System.getenv()
​
        val cl = classes.first { "java.util.Collections\$UnmodifiableMap" == it.name }
​
        val field = cl.getDeclaredField("m")
        field.isAccessible = true
        val obj = field[env]
        val map = obj as MutableMap<String, String>
        map.putAll(mapOf(key to value))
    }
}
​
class KnownProperties {
    var JAVA_HOME: String by EnvironmentDelegate()
    var sample: String by EnvironmentDelegate()
}
​
fun main() {
    val knowProps = KnownProperties()
    knowProps.sample = "2"
​
    println("Java Home: ${knowProps.JAVA_HOME}")
    println("Sample: ${knowProps.sample}")
}

在当前Java进程中设置环境变量,该进程使用依赖于所讨论的环境变量的本机代码(dll),只有在本机设置此环境变量时才有效。

这里的大多数示例都是在JVM中更改映射,但不能在本机工作。

我看到的一种方法是通过JNI,它可能也同样有效。 另一种方法是通过使用Kernel32接口(仅限windows)使用JNA平台。例如:

private static void setEnv(String key, String value) {
    if(isWindows()) {
        if (!Kernel32.INSTANCE.SetEnvironmentVariable(key, value)) {
            System.err.println("Unable to set the environemnt variable: " + key);
        }
    }
}

对于类似unix的操作系统,可以使用LibCAPI接口,但还没有尝试过。

蒂姆·瑞安的回答对我很管用……但我希望它用于Groovy(例如Spock上下文),并且simplissimo:

import java.lang.reflect.Field

def getModifiableEnvironmentMap() {
    def unmodifiableEnv = System.getenv()
    Class cl = unmodifiableEnv.getClass()
    Field field = cl.getDeclaredField("m")
    field.accessible = true
    field.get(unmodifiableEnv)
}

def clearEnvironmentVars( def keys ) {
    def savedVals = [:]
    keys.each{ key ->
        String val = modifiableEnvironmentMap.remove(key)
        // thinking about it, I'm not sure why we need this test for null
        // but haven't yet done any experiments
        if( val != null ) {
            savedVals.put( key, val )
        }
    }
    savedVals
}

def setEnvironmentVars(Map varMap) {
    modifiableEnvironmentMap.putAll(varMap)
}

// pretend existing Env Var doesn't exist
def PATHVal1 = System.env.PATH
println "PATH val1 |$PATHVal1|"
String[] keys = ["PATH", "key2", "key3"]
def savedVars = clearEnvironmentVars(keys)
def PATHVal2 = System.env.PATH
println "PATH val2 |$PATHVal2|"

// return to reality
setEnvironmentVars(savedVars)
def PATHVal3 = System.env.PATH
println "PATH val3 |$PATHVal3|"
println "System.env |$System.env|"

// pretend a non-existent Env Var exists
setEnvironmentVars( [ 'key4' : 'key4Val' ])
println "key4 val |$System.env.key4|"