Set the fields' value for Java Bean. - Java Reflection

Java examples for Reflection:Java Bean

Description

Set the fields' value for Java Bean.

Demo Code


//package com.java2s;
import java.lang.reflect.Field;

import java.util.Map;

public class Main {
    /**//from  ww w .  j  ava  2 s. c  o m
     * Set the fields' value.
     * 
     * @param bean
     * @param valMap
     */
    public static void setFieldValues(Object bean,
            Map<String, Object> valMap) {
        Class<?> cls = bean.getClass();
        //Get all fields.
        Field[] fields = cls.getDeclaredFields();

        for (Field field : fields) {
            if (valMap.containsKey(field.getName())) {
                field.setAccessible(true);
                try {
                    field.set(bean, valMap.get(field.getName()));
                } catch (IllegalArgumentException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

Related Tutorials