Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. It does not go into either the if() or the else if() section. And the maps remain empty.

Could someone figure out the issue here? Thanks

public class ClassA {
    private String optionOne = "1";
    private Int optionTwo = 2;

}


        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));
            }
        }
like image 541
Sunny Avatar asked Mar 09 '26 06:03

Sunny


1 Answers

Change getFields to getDeclaredFields and Integer.class to int.class since field optionTwo is int not Integer.

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

for (Field field : ClassA.class.getDeclaredFields()) {
    field.setAccessible(true);
    if (field.getType().equals(String.class)){
        map.put(field.getName(), (String) field.get(object));
    } else if (field.getType().equals(int.class)) {
        mapInt.put(field.getName(), (Integer) field.get(object));
    }
}
like image 183
zhh Avatar answered Mar 10 '26 18:03

zhh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!