mercredi 18 juillet 2018

Java: Converting Class member variables/values into Map - Reflection

I have an instance of a class for which I would like to create a Map which has Key as each class variable name and its Value as the value in that class variable?

I tried to use the following but it doesn't seem to work.

Could someone figure out the issue here? Thanks

        Map<String, String> map = new HashMap<>();
        Map<String, Integer> mapInt = new HashMap<>();

        for (Field field : ClassA.class.getFields()) {
            field.setAccessible(true);
            if (field.getType().equals(String.class)){
                map.put(field.getName(), (String) field.get(object));
            } else if (field.getType().equals(Integer.class)) {
                mapInt.put(field.getName(), (Integer) field.get(object));
            }
        }





Aucun commentaire:

Enregistrer un commentaire