jeudi 27 août 2020

Get HashMap with Reflection

public class First {
    public final static Map<String, String> MAP = new HashMap<>();
    static {
        MAP.put("A", "1");
        MAP.put("B", "2");
    }
}

public class Second {
    Class<?> clazz = Class.forName("First");
    Field field = clazz.getField("MAP");
    Map<String, String> newMap = (HashMap<String, String>) field.get(null); // Obviously doesn't work
}

Pretty much it. I have no trouble getting for example values of String variables, but I'm stuck with this one. Tryed to google it, failed. Also, if possible I'd like to get this Map without instantiating its class.





Aucun commentaire:

Enregistrer un commentaire