Created
May 18, 2022 22:21
-
-
Save raninho/4290af3a002e8999682c3ee53f9162c2 to your computer and use it in GitHub Desktop.
Class to create env var in Java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.google.common.annotations.VisibleForTesting; | |
import java.lang.reflect.Field; | |
import java.util.Map; | |
@VisibleForTesting | |
public class Environment { | |
public static void set(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); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment