Skip to content

Instantly share code, notes, and snippets.

@jaytaylor
Created August 21, 2014 02:41
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jaytaylor/770bc416f0dd5954cf0f to your computer and use it in GitHub Desktop.
Save jaytaylor/770bc416f0dd5954cf0f to your computer and use it in GitHub Desktop.
Setting environment variables in Scala JVM
trait EnvHacker {
/**
* Portable method for setting env vars on both *nix and Windows.
* @see http://stackoverflow.com/a/7201825/293064
*/
def setEnv(newEnv: Map[String, String]): Unit = {
try {
val processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment")
val theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment")
theEnvironmentField.setAccessible(true)
val env = theEnvironmentField.get(null).asInstanceOf[JavaMap[String, String]]
env.putAll(newEnv)
val theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment")
theCaseInsensitiveEnvironmentField.setAccessible(true)
val cienv = theCaseInsensitiveEnvironmentField.get(null).asInstanceOf[JavaMap[String, String]]
cienv.putAll(newEnv)
} catch {
case e: NoSuchFieldException =>
try {
val classes = classOf[Collections].getDeclaredClasses()
val env = System.getenv()
for (cl <- classes) {
if (cl.getName() == "java.util.Collections$UnmodifiableMap") {
val field = cl.getDeclaredField("m")
field.setAccessible(true)
val obj = field.get(env)
val map = obj.asInstanceOf[JavaMap[String, String]]
map.clear()
map.putAll(newEnv)
}
}
} catch {
case e2: Exception => e2.printStackTrace()
}
case e1: Exception => e1.printStackTrace()
}
}
}
@JesusZV
Copy link

JesusZV commented Jun 11, 2019

How can i get the JavaMap object

@vpatryshev
Copy link

@JesusZV import java.util.{Map => JavaMap}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment