質問

Javaから環境変数を設定するにはどうすればよいですか? ProcessBuilderを使用して、サブプロセスに対してこれを実行できることがわかります。 。ただし、開始するサブプロセスがいくつかあるため、現在のプロセスの環境を変更し、サブプロセスにそれを継承させます。

単一の環境変数を取得するためのSystem.getenv(String)があります。 Mapで環境変数の完全なセットのSystem.getenv()を取得することもできます。しかし、そのput()UnsupportedOperationExceptionを呼び出すと、System.setenv()がスローされます。明らかに、環境が読み取り専用であることを意味します。そして、<=>はありません。

では、現在実行中のプロセスに環境変数を設定する方法はありますか?もしそうなら、どのように?そうでない場合、その根拠は何ですか? (これはJavaであるため、環境に触れるなど、移植性のない時代遅れの悪いことをすべきではないのですか?)そして、そうでない場合は、環境変数の変更を管理するための良い提案をいくつかに提供する必要がありますサブプロセス?

役に立ちましたか?

解決

  

(これはJavaであるため、環境に触れるなど、移植性のない時代遅れの邪悪なことをすべきではないのですか?)

頭に釘を打ったと思います。

負担を軽減する可能な方法は、メソッドを除外することです

void setUpEnvironment(ProcessBuilder builder) {
    Map<String, String> env = builder.environment();
    // blah blah
}

開始する前にProcessBuilder sを渡します。

また、おそらくこれを既に知っているかもしれませんが、同じ<=>で複数のプロセスを開始できます。したがって、サブプロセスが同じ場合、この設定を何度も繰り返す必要はありません。

他のヒント

単体テスト用に特定の環境値を設定する必要があるシナリオで使用するには、次のハックが役立つ場合があります。 JVM全体の環境変数を変更します(したがって、テスト後に変更を必ずリセットしてください)が、システム環境は変更しません。

エドワード・キャンベルと匿名による2つの汚いハックの組み合わせが最も効果的であることがわかりました。1つはLinuxでは機能せず、1つは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);
      }
    }
  }
}

これは魅力のように機能します。これらのハッキングの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);
        }
    }
}

または単一の変数を追加/更新し、joshwolfeの提案に従ってループを削除します。

@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);
  }
// 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);
}

Androidでは、インターフェースはLibcore.osを介して一種の隠されたAPIとして公開されます。

Libcore.os.setenv("VAR", "value", bOverwrite);
Libcore.os.getenv("VAR"));

LibcoreクラスとインターフェイスOSはパブリックです。クラス宣言が欠落しているため、リンカーに表示する必要があります。クラスをアプリケーションに追加する必要はありませんが、含まれていても害はありません。

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;
}

Linuxのみ

単一の環境変数の設定(Edward Campbellの回答に基づく):

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。

SystemUtil.setEnv("SHELL", "/bin/bash");

この後にSystem.getenv("SHELL")を呼び出すと、"/bin/bash"が返されます。

Androidは実際にはJavaではないため、@ pushy / @ anonymous / @ Edward CampbellのソリューションはAndroidでは機能しません。具体的には、Androidにはjava.lang.ProcessEnvironmentがまったくありません。しかし、Androidの方が簡単であることがわかりました。POSIXsetenv()

に対してJNI呼び出しを行うだけです。

C / JNIの場合:

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;
}

およびJavaの場合:

public class Posix {

    public static native int setenv(String key, String value, boolean overwrite);

    private void runTest() {
        Posix.setenv("LD_LIBRARY_PATH", "foo", true);
    }
}

これは、@ paul-blairの回答をJavaに変換したものです。これには、paul blairが指摘したクリーンアップと、@ Edward Campbellで構成される@pushyのコード内にあったと思われるいくつかの間違いが含まれます。匿名。

このコードをテストでのみ使用する必要があることを強調することはできず、非常にハッキングです。しかし、テストで環境設定が必要な場合は、まさに私が必要なものです。

これには、コードを実行している両方のWindowsでコードが動作するようにするためのマイナーなタッチも含まれます

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)

およびCentosが実行されている

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));
}

オンラインで調べてみると、JNIでこれを実行できる可能性があるようです。その後、Cからputenv()を呼び出す必要があり、(おそらく)WindowsとUNIXの両方で機能する方法で呼び出す必要があります。

それがすべて可能であれば、私をまっすぐなジャケットに入れずに、Java自体がこれをサポートするのは確かに難しくありません。

他の場所でPerlを話す友人は、これは環境変数がグローバルなプロセスであり、Javaが優れた設計のための良好な分離を目指しているためだと示唆しています。

上記のpushyの答えを試してみたところ、ほとんどの場合うまくいきました。ただし、特定の状況では、次の例外が表示されます。

java.lang.String cannot be cast to java.lang.ProcessEnvironment$Variable

ProcessEnvironment.の特定の内部クラスの実装により、メソッドが複数回呼び出されたときに発生することが判明しました。setEnv(..)メソッドが複数回呼び出された場合、キーが<= >マップ、それらは文字列になり(theEnvironmentの最初の呼び出しによって文字列として入れられます)、マップのジェネリック型setEnv(...)にキャストできません。これはVariable,

のプライベート内部クラスです

修正版(Scala内)は以下のとおりです。うまくいけば、Javaに持ち越すのがそれほど難しくないことを願っています。

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()
  }
}

このスレッドを見つけたほとんどの人と同じように、私はいくつかの単体テストを書いていたので、環境変数を変更してテストを実行するための正しい条件を設定する必要がありました。しかし、私は最も支持された答えにはいくつかの問題があり、かつ/または非常に不可解であるか、過度に複雑であることがわかりました。うまくいけば、他の人がより迅速にソリューションを整理するのに役立つでしょう。

最初に、@ Hubert Grzeskowiakのソリューションが最も簡単であることが最終的にわかりました。私は最初にそこに来ていたらよかったのにと思います。 @Edward Campbellの回答に基づいていますが、ループ検索の複雑さはありません。

しかし、私は@pushyのソリューションから始めました。 @anonymousと@Edward Campbellのコンボです。 @pushyは、LinuxとWindowsの両方の環境をカバーするには両方のアプローチが必要であると主張しています。私はOS Xで実行していますが、両方が動作することがわかりました(@anonymousアプローチの問題が修正されると)。他の人が指摘したように、このソリューションはほとんどの場合機能しますが、すべてではありません。

ほとんどの混乱の原因は、「環境」フィールドで動作する@anonymousのソリューションにあると思います。 ProcessEnvironment 構造、「theEnvironment」はMap <!> lt;ではありません。文字列、文字列<!> gt;むしろMap <!> lt;変数、値<!> gt;。マップのクリアは正常に機能しますが、putAll操作はマップを再構築しますMap <!> lt;文字列、文字列<!> gt;。これは、Map <!> lt;を予期する通常のAPIを使用してデータ構造に対して後続の操作を実行するときに問題を引き起こす可能性があります。変数、値<!> gt;。また、個々の要素へのアクセス/削除も問題です。解決策は、「theUnmodifiableEnvironment」を介して間接的に「theEnvironment」にアクセスすることです。ただし、これはタイプ UnmodifiableMap アクセスは、UnmodifiableMapタイプのプライベート変数「m」を介して行う必要があります。以下のコードのgetModifiableEnvironmentMap2を参照してください。

私の場合、テスト用に環境変数の一部を削除する必要がありました(他の環境変数は変更しないでください)。次に、テスト後に環境変数を以前の状態に戻したいと思いました。以下のルーチンにより、簡単に実行できます。 OS XでgetModifiableEnvironmentMapの両方のバージョンをテストしましたが、どちらも同等に機能します。このスレッドのコメントに基づいていますが、環境に応じて、一方が他方よりも適切な選択になる場合があります。

注: 'theCaseInsensitiveEnvironmentField'へのアクセスは含めませんでした。これは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);
}

これは@pushyの悪のKotlin悪バージョンです回答 =)

@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)
            }
        }
    }

少なくともmacOS Mojaveで動作しています。

エドワードの答えに基づいて最近作成したKotlinの実装:

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)
    }
}

-Dを使用すると、初期Javaプロセスにパラメーターを渡すことができます:

java -cp <classpath> -Dkey1=value -Dkey2=value ...
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top