Pramod Karandikar
Pramod Karandikar

Reputation: 5329

Get fields and their values at runtime using Java Reflection

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.

Upvotes: 1

Views: 2291

Answers (3)

Pramod Karandikar
Pramod Karandikar

Reputation: 5329

I missed field.get(Object) method. This will resolve the issue.

Upvotes: 1

user2184773
user2184773

Reputation: 31

how about this method in Filed :Object get(Object obj) this method returns the value of the field represented by this Field, on the specified object.

Upvotes: 1

field.getType() returns the type of the field (int.class, Date.class, etc). You can easily perform different actions depending on its return value.

Class<?> type = field.getType();
if(type == int.class) {
    // load an int
} else if(type == Date.class) {
    // load a Date
} else if(type == String.class) {
    // load a String
}
// etc

Upvotes: -1

Related Questions