Get all fields' value from Java Bean and put them to a map. - Java Reflection

Java examples for Reflection:Java Bean

Description

Get all fields' value from Java Bean and put them to a map.

Demo Code


//package com.java2s;
import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;

public class Main {
    public static void main(String[] argv) throws Exception {
        Object bean = "java2s.com";
        System.out.println(getFieldValueMap(bean));
    }/*from   w w w  .  j  a v  a2  s.  c o  m*/

    /**
     * Get all fields' value and put them to a map.
     * 
     * @param bean
     * @return Map
     */
    public static Map<String, Object> getFieldValueMap(Object bean) {
        Class<?> cls = bean.getClass();
        Map<String, Object> valueMap = new HashMap<String, Object>();
        // Get all fields.
        Field[] fields = cls.getDeclaredFields();

        for (Field field : fields) {
            try {
                field.setAccessible(true);
                Object value = field.get(bean);
                //            if(value == null) {
                //               valueMap.put(field.getName(), "");
                //               continue;
                //            }
                valueMap.put(field.getName(), value);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        return valueMap;
    }
}

Related Tutorials