如何从Java设置环境变量?
如何从Java设置环境变量?我看到我可以使用为子流程执行此操作。不过,我有几个子流程要启动,所以我宁愿修改当前流程的环境,让子流程继承它 有一个如何从Java设置环境变量?,java,environment-variables,jython,Java,Environment Variables,Jython,如何从Java设置环境变量?我看到我可以使用为子流程执行此操作。不过,我有几个子流程要启动,所以我宁愿修改当前流程的环境,让子流程继承它 有一个System.getenv(String)用于获取单个环境变量。我还可以使用System.getenv()获得环境变量整套的映射。但是,在Map上调用put()会抛出一个不支持的操作异常——显然,这意味着环境是只读的。而且,没有System.setenv() 那么,有没有办法在当前运行的进程中设置环境变量?如果是,怎么做?如果没有,理由是什么?(是因为这
System.getenv(String)
用于获取单个环境变量。我还可以使用System.getenv()
获得环境变量整套的映射。但是,在Map
上调用put()
会抛出一个不支持的操作异常
——显然,这意味着环境是只读的。而且,没有System.setenv()
那么,有没有办法在当前运行的进程中设置环境变量?如果是,怎么做?如果没有,理由是什么?(是因为这是Java,所以我不应该做不可移植的过时的事情,比如触摸我的环境吗?)如果不是,有什么好的建议来管理环境变量更改,我需要将这些更改提供给几个子流程吗?您可以使用-D将参数传递到初始Java流程中:
java -cp <classpath> -Dkey1=value -Dkey2=value ...
java-cp-Dkey1=value-Dkey2=value。。。
(是因为这是Java,所以我不应该做一些不可移植的过时的事情,比如触摸我的环境?)
我认为你一针见血
减轻负担的一种可能的方法是找出一种方法
void setUpEnvironment(ProcessBuilder builder) {
Map<String, String> env = builder.environment();
// blah blah
}
void设置环境(ProcessBuilder){
Map env=builder.environment();
//废话
}
并在启动前将任何ProcessBuilder
s传递给它
另外,您可能已经知道这一点,但可以使用相同的ProcessBuilder
启动多个进程。因此,如果您的子流程是相同的,那么您不需要反复执行此设置。在网上浏览,似乎可以使用JNI执行此操作。然后,您必须从C调用putenv(),并且(大概)必须以一种在Windows和UNIX上都能工作的方式来执行
如果所有这些都能做到,那么Java本身支持这一点肯定不会太难,而不是让我穿上一件紧身衣
其他地方一位会说Perl的朋友指出,这是因为环境变量是进程全局变量,Java正在努力实现良好的设计隔离。publicstaticvoidset(Map newenv)抛出异常{
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);
}
}
}
Class[]classes=Collections.Class.getDeclaredClasses();
Map env=System.getenv();
对于(类别cl:类别){
if(“java.util.Collections$UnmodifiableMap”.equals(cl.getName())){
字段字段=cl.getDeclaredField(“m”);
字段。setAccessible(true);
Object obj=field.get(env);
Map Map=(Map)obj;
map.clear();
普塔尔地图(新环境);
}
}
}
或者根据JoshWolfe的建议添加/更新单个var并删除循环
@SuppressWarnings({ "unchecked" })
public static void updateEnv(String name, String val) throws ReflectiveOperationException {
Map<String, String> env = System.getenv();
Field field = env.getClass().getDeclaredField("m");
field.setAccessible(true);
((Map<String, String>) field.get(env)).put(name, val);
}
@SuppressWarnings({“unchecked”})
公共静态void updateEnv(字符串名称,字符串值)引发ReflectiveOperationException{
Map env=System.getenv();
Field=env.getClass().getDeclaredField(“m”);
字段。setAccessible(true);
((Map)field.get(env)).put(name,val);
}
//这是一个肮脏的黑客攻击-但是对于单元测试应该是可以的。
私有void setNewEnvironmentHack(映射newenv)引发异常
{
类ProcessEnvironment类=Class.forName(“java.lang.ProcessEnvironment”);
Field theEnvironment Field=processEnvironmentClass.getDeclaredField(“theEnvironment”);
环境字段。设置为可访问(true);
Map env=(Map)环境字段.get(null);
环境清除();
环境保护局(新环境);
字段theCaseInsensitiveEnvironmentField=processEnvironmentClass.getDeclaredField(“theCaseInsensitiveEnvironment”);
CaseInsensitiveEnvironmentField.setAccessible(true);
Map cienv=(Map)CaseInsensitiveEnvironmentField.get(null);
cienv.clear();
cienv.putAll(新环境);
}
对于需要为单元测试设置特定环境值的场景,您可能会发现以下hack很有用。它将在整个JVM中更改环境变量(因此请确保在测试后重置任何更改),但不会更改系统环境
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}")
}
我发现Edward Campbell和anonymous的两个肮脏的黑客组合效果最好,因为其中一个在linux下不工作,另一个在windows 7下不工作。所以为了得到一个多平台的邪恶黑客,我将它们结合起来:
protected static void setEnv(Map<String, String> newenv) throws Exception {
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) {
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);
}
}
}
}
受保护的静态void setEnv(Map newenv)引发异常{
试一试{
类ProcessEnvironment类=Class.forName(“java.lang.ProcessEnvironment”);
Field theEnvironment Field=processEnvironmentClass.getDeclaredField(“theEnvironment”);
环境字段。设置为可访问(true);
Map env=(Map)环境字段.get(null);
环境保护局(新环境);
字段theCaseInsensitiveEnvironmentField=processEnvironmentClass.getDeclaredField(“theCaseInsensitiveEnvironment”);
CaseInsensitiveEnvironmentField.setAccessible(true);
Map cienv=(Map)CaseInsensitiveEnvironmentField.get(null);
cienv.putAll(新环境);
}捕获(无此字段例外){
Class[]classes=Collections.Class.getDeclaredClasses();
Map env=System.getenv();
对于(类别cl:类别){
if(“java.util.Collections$UnmodifiableMap”.equals(cl.getName())){
字段字段=cl.getDeclaredField(“m”);
字段。setAccessible(true);
Object obj=field.get(env);
Map Map=(Map)obj;
map.clear();
普塔尔地图(新环境);
}
}
}
}
这很有魅力。完全归功于这两位黑客的作者。尝试了上面pushy的答案,大部分都奏效了。但是,在某些情况下,我会看到以下例外情况:
java.lang.String cannot be cast to java.lang.ProcessEnvironment$Variable
由于impl,当方法被多次调用时,就会发生这种情况
def setEnv(newenv: java.util.Map[String, String]): Unit = {
try {
val processEnvironmentClass = JavaClass.forName("java.lang.ProcessEnvironment")
val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
theEnvironmentField.setAccessible(true)
val variableClass = JavaClass.forName("java.lang.ProcessEnvironment$Variable")
val convertToVariable = variableClass.getMethod("valueOf", classOf[java.lang.String])
convertToVariable.setAccessible(true)
val valueClass = JavaClass.forName("java.lang.ProcessEnvironment$Value")
val convertToValue = valueClass.getMethod("valueOf", classOf[java.lang.String])
convertToValue.setAccessible(true)
val sampleVariable = convertToVariable.invoke(null, "")
val sampleValue = convertToValue.invoke(null, "")
val env = theEnvironmentField.get(null).asInstanceOf[java.util.Map[sampleVariable.type, sampleValue.type]]
newenv.foreach { case (k, v) => {
val variable = convertToVariable.invoke(null, k).asInstanceOf[sampleVariable.type]
val value = convertToValue.invoke(null, v).asInstanceOf[sampleValue.type]
env.put(variable, value)
}
}
val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
theCaseInsensitiveEnvironmentField.setAccessible(true)
val cienv = theCaseInsensitiveEnvironmentField.get(null).asInstanceOf[java.util.Map[String, String]]
cienv.putAll(newenv);
}
catch {
case e : NoSuchFieldException => {
try {
val classes = classOf[java.util.Collections].getDeclaredClasses
val env = System.getenv()
classes foreach (cl => {
if("java.util.Collections$UnmodifiableMap" == cl.getName) {
val field = cl.getDeclaredField("m")
field.setAccessible(true)
val map = field.get(env).asInstanceOf[java.util.Map[String, String]]
// map.clear() // Not sure why this was in the code. It means we need to set all required environment variables.
map.putAll(newenv)
}
})
} catch {
case e2: Exception => e2.printStackTrace()
}
}
case e1: Exception => e1.printStackTrace()
}
}
JNIEXPORT jint JNICALL Java_com_example_posixtest_Posix_setenv
(JNIEnv* env, jclass clazz, jstring key, jstring value, jboolean overwrite)
{
char* k = (char *) (*env)->GetStringUTFChars(env, key, NULL);
char* v = (char *) (*env)->GetStringUTFChars(env, value, NULL);
int err = setenv(k, v, overwrite);
(*env)->ReleaseStringUTFChars(env, key, k);
(*env)->ReleaseStringUTFChars(env, value, v);
return err;
}
Libcore.os.setenv("VAR", "value", bOverwrite);
Libcore.os.getenv("VAR"));
package libcore.io;
public final class Libcore {
private Libcore() { }
public static Os os;
}
package libcore.io;
public interface Os {
public String getenv(String name);
public void setenv(String name, String value, boolean overwrite) throws ErrnoException;
}
java version "1.8.0_92"
Java(TM) SE Runtime Environment (build 1.8.0_92-b14)
Java HotSpot(TM) 64-Bit Server VM (build 25.92-b14, mixed mode)
openjdk version "1.8.0_91"
OpenJDK Runtime Environment (build 1.8.0_91-b14)
OpenJDK 64-Bit Server VM (build 25.91-b14, mixed mode)
/**
* Sets an environment variable FOR THE CURRENT RUN OF THE JVM
* Does not actually modify the system's environment variables,
* but rather only the copy of the variables that java has taken,
* and hence should only be used for testing purposes!
* @param key The Name of the variable to set
* @param value The value of the variable to set
*/
@SuppressWarnings("unchecked")
public static <K,V> void setenv(final String key, final String value) {
try {
/// we obtain the actual environment
final Class<?> processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
final Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
final boolean environmentAccessibility = theEnvironmentField.isAccessible();
theEnvironmentField.setAccessible(true);
final Map<K,V> env = (Map<K, V>) theEnvironmentField.get(null);
if (SystemUtils.IS_OS_WINDOWS) {
// This is all that is needed on windows running java jdk 1.8.0_92
if (value == null) {
env.remove(key);
} else {
env.put((K) key, (V) value);
}
} else {
// This is triggered to work on openjdk 1.8.0_91
// The ProcessEnvironment$Variable is the key of the map
final Class<K> variableClass = (Class<K>) Class.forName("java.lang.ProcessEnvironment$Variable");
final Method convertToVariable = variableClass.getMethod("valueOf", String.class);
final boolean conversionVariableAccessibility = convertToVariable.isAccessible();
convertToVariable.setAccessible(true);
// The ProcessEnvironment$Value is the value fo the map
final Class<V> valueClass = (Class<V>) Class.forName("java.lang.ProcessEnvironment$Value");
final Method convertToValue = valueClass.getMethod("valueOf", String.class);
final boolean conversionValueAccessibility = convertToValue.isAccessible();
convertToValue.setAccessible(true);
if (value == null) {
env.remove(convertToVariable.invoke(null, key));
} else {
// we place the new value inside the map after conversion so as to
// avoid class cast exceptions when rerunning this code
env.put((K) convertToVariable.invoke(null, key), (V) convertToValue.invoke(null, value));
// reset accessibility to what they were
convertToValue.setAccessible(conversionValueAccessibility);
convertToVariable.setAccessible(conversionVariableAccessibility);
}
}
// reset environment accessibility
theEnvironmentField.setAccessible(environmentAccessibility);
// we apply the same to the case insensitive environment
final Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
final boolean insensitiveAccessibility = theCaseInsensitiveEnvironmentField.isAccessible();
theCaseInsensitiveEnvironmentField.setAccessible(true);
// Not entirely sure if this needs to be casted to ProcessEnvironment$Variable and $Value as well
final Map<String, String> cienv = (Map<String, String>) theCaseInsensitiveEnvironmentField.get(null);
if (value == null) {
// remove if null
cienv.remove(key);
} else {
cienv.put(key, value);
}
theCaseInsensitiveEnvironmentField.setAccessible(insensitiveAccessibility);
} catch (final ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InvocationTargetException e) {
throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+">", e);
} catch (final NoSuchFieldException e) {
// we could not find theEnvironment
final Map<String, String> env = System.getenv();
Stream.of(Collections.class.getDeclaredClasses())
// obtain the declared classes of type $UnmodifiableMap
.filter(c1 -> "java.util.Collections$UnmodifiableMap".equals(c1.getName()))
.map(c1 -> {
try {
return c1.getDeclaredField("m");
} catch (final NoSuchFieldException e1) {
throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+"> when locating in-class memory map of environment", e1);
}
})
.forEach(field -> {
try {
final boolean fieldAccessibility = field.isAccessible();
field.setAccessible(true);
// we obtain the environment
final Map<String, String> map = (Map<String, String>) field.get(env);
if (value == null) {
// remove if null
map.remove(key);
} else {
map.put(key, value);
}
// reset accessibility
field.setAccessible(fieldAccessibility);
} catch (final ConcurrentModificationException e1) {
// This may happen if we keep backups of the environment before calling this method
// as the map that we kept as a backup may be picked up inside this block.
// So we simply skip this attempt and continue adjusting the other maps
// To avoid this one should always keep individual keys/value backups not the entire map
LOGGER.info("Attempted to modify source map: "+field.getDeclaringClass()+"#"+field.getName(), e1);
} catch (final IllegalAccessException e1) {
throw new IllegalStateException("Failed setting environment variable <"+key+"> to <"+value+">. Unable to access field!", e1);
}
});
}
LOGGER.info("Set environment variable <"+key+"> to <"+value+">. Sanity Check: "+System.getenv(key));
}
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);
}
}
SystemUtil.setEnv("SHELL", "/bin/bash");
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);
}
fun setEnv(newEnv: Map<String, String>) {
val unmodifiableMapClass = Collections.unmodifiableMap<Any, Any>(mapOf()).javaClass
with(unmodifiableMapClass.getDeclaredField("m")) {
isAccessible = true
@Suppress("UNCHECKED_CAST")
get(System.getenv()) as MutableMap<String, String>
}.apply {
clear()
putAll(newEnv)
}
}
@Suppress("UNCHECKED_CAST")
@Throws(Exception::class)
fun setEnv(newenv: Map<String, String>) {
try {
val processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment")
val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
theEnvironmentField.isAccessible = true
val env = theEnvironmentField.get(null) as MutableMap<String, String>
env.putAll(newenv)
val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
theCaseInsensitiveEnvironmentField.isAccessible = true
val cienv = theCaseInsensitiveEnvironmentField.get(null) as MutableMap<String, String>
cienv.putAll(newenv)
} catch (e: NoSuchFieldException) {
val classes = Collections::class.java.getDeclaredClasses()
val env = System.getenv()
for (cl in classes) {
if ("java.util.Collections\$UnmodifiableMap" == cl.getName()) {
val field = cl.getDeclaredField("m")
field.setAccessible(true)
val obj = field.get(env)
val map = obj as MutableMap<String, String>
map.clear()
map.putAll(newenv)
}
}
}
was.app.config.properties.toSystemProperties
def set_env(newenv):
from java.lang import Class
process_environment = Class.forName("java.lang.ProcessEnvironment")
environment_field = process_environment.getDeclaredField("theEnvironment")
environment_field.setAccessible(True)
env = environment_field.get(None)
env.putAll(newenv)
invariant_environment_field = process_environment.getDeclaredField("theCaseInsensitiveEnvironment");
invariant_environment_field.setAccessible(True)
invevn = invariant_environment_field.get(None)
invevn.putAll(newenv)
old_environ = dict(os.environ)
old_environ['EPM_ORACLE_HOME'] = r"E:\Oracle\Middleware\EPMSystem11R1"
set_env(old_environ)
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|"
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}")
}
setx JAVA_LOC C:/Java/JDK
String cmdCommand = "setx JAVA_LOC " + "C:/Java/JDK";
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command("cmd.exe", "/c", cmdCommand);
processBuilder.start();