3

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));
            }
        }
5
  • Both the maps are empty. (updated the question) Commented Jul 19, 2018 at 5:28
  • 1
    Use getDeclaredFields, and it is int.class not Integer.class. Commented Jul 19, 2018 at 5:28
  • @zhh ok that works for String.class now. But the int variables are not going into mapInt. is the equality check correct? Commented Jul 19, 2018 at 5:36
  • Not sure what Int type is - is it int or Integer? Commented Jul 19, 2018 at 5:38
  • You should check for int.class not Integer.class. Commented Jul 19, 2018 at 5:38

2 Answers 2

2

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));
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

With the help of @zhh I was able to fix the issue as follows:

  1. ClassA.class.getDeclaredFields() instead of ClassA.class.getFields()
  2. Integer.TYPE instead of Integer.class
 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(Integer.TYPE)) {
                    mapInt.put(field.getName(), (Integer) field.get(object));
                }
            }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.