0

U tried various solutions like ProcessBuilder and Runtime to update an environment variable, but none work. I have used reflection, but it does not seem to work as it's an unmodifiableMap.

private void updateEnvVars(Map<String, String> kafkaProps) {
    try {
        Class[] classes = Collections.class.getDeclaredClasses();
        System.out.println("Total Classes : " + classes.length);
        Map<String, String> env = System.getenv();
        for (Class cl : classes) {
            System.out.println("ClassName: " + cl.getFields().toString());
            if ("java.util.Collections$UnmodifiableMap".equals(cl.getName())) {
                Field field = null;
                field = cl.getDeclaredField("m");
                field.setAccessible(true);
                Object obj = field.get(env);
                final Map<String, String> objectObjectHashMap = new HashMap<>();
                objectObjectHashMap.putAll(System.getenv());
                objectObjectHashMap.putAll(kafkaProps);

                Map<String, String> map = (Map<String, String>) obj;
                //java.util.Collections.unmodifiableMap<String, String>
                //final Map<String, String> stringMap = Collections.unmodifiableMap(map);
                map.clear();
                map.putAll(objectObjectHashMap);
        }
    }
Mark Rotteveel
  • 90,369
  • 161
  • 124
  • 175
RamRapolu
  • 1
  • 5
  • tried that solution @MatteoNNZ, but it does not work for me. all 3 solutions mentioned in the web page. it complains about unmodifiableMap, tried to clear and then readd them. – RamRapolu May 24 '22 at 13:41

0 Answers0