Fill Bean Data from HashMap using Reflection


Introduction:

This example shows how to fill the values in a bean from a HashMap using Reflection. In the HashMap, key is the field name & value is the value of that field.

Quick Start:

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

/**
 * Fill Bean Data from HashMap using Reflection
 * 
 * @author Debopam Pal, Software Developer, NIC, India.
 * @param fieldValueMapping Mapping of field & its value where 'key' is the field & 'value' is the value.
 * @param cls The Bean Class which have to be filled.
 * @return The filled object of that Bean Class.
 */
public static Object FilledBean(Map<String, Object> fieldValueMapping, Class cls) {
    Object obj = null;
    try {
        obj = cls.newInstance();
        Field[] fields = cls.getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            for (Map.Entry<String, Object> entry : fieldValueMapping.entrySet()) {
                if (field.getName().equals(entry.getKey())) {
                    field.set(obj, entry.getValue());
                }
            }
        }
    } catch (InstantiationException ex) {
        // do something...
    } catch (IllegalAccessException ex) {
        // do something...
    }

    return obj;
}

Sample Bean Class:

import java.util.Date;

public class ReflectionDemo {

    private String variable;
    private Date log_dt;
    private double price;

    /**
     * @return the variable
     */
    public String getVariable() {
        return variable;
    }

    /**
     * @param variable the variable to set
     */
    public void setVariable(String variable) {
        this.variable = variable;
    }

    /**
     * @return the log_dt
     */
    public Date getLog_dt() {
        return log_dt;
    }

    /**
     * @param log_dt the log_dt to set
     */
    public void setLog_dt(Date log_dt) {
        this.log_dt = log_dt;
    }

    /**
     * @return the price
     */
    public double getPrice() {
        return price;
    }

    /**
     * @param price the price to set
     */
    public void setPrice(double price) {
        this.price = price;
    }
}

How to Call:

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

public static void main(String[] args) {
    Map<String, Object> myMap = new HashMap<String, Object>();
    myMap.put("variable", "some var");
    myMap.put("log_dt", Calendar.getInstance().getTime());
    myMap.put("price", 123.35);
    ReflectionDemo rd = (ReflectionDemo)FilledBean(myMap, ReflectionDemo.class);
    System.out.print(rd.getLog_dt());    // Sat May 31 02:29:51 IST
    System.out.print(rd.getPrice());     // 123.35
    System.out.print(rd.getVariable());  // some var
}

If you've any doubt, please post your questions. If you really like this article, please share it.

Don’t forget to Vote or Comment about my writing.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s