I am trying to get fields and their values of an object at runtime. Below is the code sample:
public static int calculateProfileStrenght(Object inputObj, Map<String, Integer> configMap) throws IllegalArgumentException, IllegalAccessException { int someValue= 0; for (Entry<String, Integer> entry : configMap.entrySet()) { System.out.println("Key=" + entry.getKey() + ", Value="+ entry.getValue()); try { Field field = inputObj.getClass().getDeclaredField(entry.getKey()); } catch (NoSuchFieldException e) { System.out.println("No such field: "+entry.getKey()); } } return someValue; } As shown above, the Map contains key-value pairs, where the key is going to be the field name (or variable name) from inputObj. I need to read the value of this field from inputObj. The datatype of the fields are String, int, Date, etc. inputObj
public class UserDetails { private int userId; private String userName; private Date joinedDate; private Address homeAddress; private String description; // getters and setters } I can't do field.getLong or getChar, etc since the method is generic and doesn't know about the datatypes of the fields of inputObj.
I need to read the field values in the for loop and apply the business logic. Is this even possible? I tried a lot of ways but to no luck. Any references/pointers are appreciated.