Skip to content

Instantly share code, notes, and snippets.

@raninho
Created May 18, 2022 22:21
Show Gist options
  • Save raninho/4290af3a002e8999682c3ee53f9162c2 to your computer and use it in GitHub Desktop.
Save raninho/4290af3a002e8999682c3ee53f9162c2 to your computer and use it in GitHub Desktop.
Class to create env var in Java
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