How to modify environment variable in JAVA.

We can get the environment variable using java System.getenv("env-name").
But there is no setter for this.
You can set it like this


import java.lang.reflect.Field;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;


public class Test {

public static void main(String[] args) throws Exception {
Map map = System.getenv();
Map newmap = new HashMap();
newmap.putAll(map);
newmap.put("abc", "----------");
setEnv(newmap);
System.out.println(map);
System.out.println("done");
System.out.println(System.getenv("abc"));
newmap.remove("abc");
setEnv(newmap);
System.out.println(System.getenv("abc"));
}
private static void setEnv(Map newenv)
{
 try
   {
       Class processEnvironmentClass = Class.forName("java.lang.ProcessEnvironment");
       Field theEnvironmentField = processEnvironmentClass.getDeclaredField("theEnvironment");
       theEnvironmentField.setAccessible(true);
       Map env = (Map) theEnvironmentField.get(null);
       env.putAll(newenv);
       Field theCaseInsensitiveEnvironmentField = processEnvironmentClass.getDeclaredField("theCaseInsensitiveEnvironment");
       theCaseInsensitiveEnvironmentField.setAccessible(true);
       Map cienv = (Map)     theCaseInsensitiveEnvironmentField.get(null);
       cienv.putAll(newenv);
   }
   catch (NoSuchFieldException e)
   {
     try {
       Class[] classes = Collections.class.getDeclaredClasses();
       Map 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 map = (Map) obj;
               map.clear();
               map.putAll(newenv);
           }
       }
     } catch (Exception e2) {
       System.out.println(e2);
     }
   } catch (Exception e1) {
    System.out.println(e1);
   } 
}
}

No comments:

Post a Comment