[英]Setting environment variable in Java 8
我有與此類似的代碼(更新環境變量):
private static void setEnv(Map<String, String> envs) {
try {
Class<?> pec = Class.forName("java.lang.ProcessEnvironment");
Field tef = pec.getDeclaredField("theEnvironment");
tef.setAccessible(true);
Map<String, String> env = (Map<String, String>) tef.get(null);
env.clear();
env.putAll(envs);
Field tcief = pec.getDeclaredField("theCaseInsensitiveEnvironment");
tcief.setAccessible(true);
Map<String, String> cienv = (Map<String, String>) tcief.get(null);
cienv.clear();
cienv.putAll(envs);
} catch (Exception e) {
logger.printStackTrace(e);
}
}
我已經為此代碼編寫了一些單元測試,現在我正在 Java 8 (1.8.0) 上進行測試。 此代碼不適用於在 JUnit 中Run
,但在作為Debug
運行時有效(帶斷點和不帶斷點)。 不起作用意味着我得到這樣的環境變量(PATH)
String path = System.getenv("PATH");
我看到沒有我的路徑( c:\\\\temp
)。 在 Java 7 (1.7.0_51) 上測試工作正常,所有 Java 都是 32 位的,我沒有使用額外的線程。 你有什么想法如何解決這個問題嗎?
問題在於區分大小寫的鍵。 參數envs
被創建為
Map<String, String> envs = new HashMap<String, String>();
但將其創建為
Map<String, String> envs = new TreeMap<String, String>(String.CASE_INSENSITIVE_ORDER);
解決了這個問題。 我得到了不同的結果env["Path"]
, env["PATH"]
等等。
您也可以使用 System Stubs 實現此目的 - https://github.com/webcompere/system-stubs
Map<String, String> someMap = ...; // work out the env variables
EnvironmentVariables environmentVariables = new EnvironmentVariables(someMap);
當對象處於活動狀態時,環境變量將應用於環境。 這是通過它的 JUnit 4 或 5 插件實現的,或者通過使用對象上的execute
方法來包裝可執行代碼來實現。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.