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));
}
}
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));
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With