Click here to Skip to main content
15,884,099 members
Articles / Programming Languages / Java

Fill Bean Data from HashMap using Reflection

Rate me:
Please Sign up or sign in to vote.
0.00/5 (No votes)
1 Jun 2014CPOL 13.9K   3  
This example shows how to fill the values in a bean from a 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

Java
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

Java
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

Java
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 have any doubts, please post your questions. If you really like this article, please share it.

Don’t forget to vote or comment about my writing.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer National Informatics Centre (NIC)
India India
Hello! Myself Debopam Pal. I've completed my MCA degree from West Bengal University of Technology at 2013. I'm from India. I’ve started to work with MS Technologies in 2013 specially in C# 4.0, ASP.NET 4.0. I've also worked in PHP 5. Now I work in JAVA/J2EE, Struts2. Currently I'm involved in a e-Governance Project since Jan, 2014. In my leisure time I write Blog, Articles as I think that every developer should contribute something otherwise resource will be finished one day. Thank you for your time.

Visit: Linkedin Profile | Facebook Profile | Google+ Profile | CodeProject Profile

Comments and Discussions

 
-- There are no messages in this forum --