Friday, May 2, 2014

Getting All Field Names and their corresponding values using Java Reflection

A Java Class: User.java

package com.pkm.reflection;

public class User {
    String firstName;    
    String lastname;
}

Example Runner Class: GetAllFieldsAndValues.java

package com.pkm.reflection;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class GetAllFieldsAndValues {
    public static void main(String[] args) {
        User user = new User();
        user.firstName = "Pritom";
        user.lastname = "Mondal";
        try {
            Map dataMap = GetAllFieldsAndValues.collectFieldValues(user);
            for (Object entry : dataMap.entrySet()) {
                Map.Entry mapEntry = (Map.Entry) entry;
		System.out.println("Key : " + mapEntry.getKey() + ", Value : "
			+ mapEntry.getValue());
            }
        } catch (Exception ex) {
            System.out.println("\n\nError: " + ex.getMessage());
        }
    }
    
    public static Map collectFieldValues(Object object) throws Exception {
        Map dataMap = new HashMap();
        Class obj = object.getClass();
        for (Field field : obj.getDeclaredFields()) {
            field.setAccessible(true);
            Object value = field.get(object);
            dataMap.put(field.getName(), value);
        }
        
        return dataMap;
    }
}

Example Output:

Key : lastname, Value : Mondal
Key : firstName, Value : Pritom

No comments:

Post a Comment