convert Map to Java Bean - Android java.lang.reflect

Android examples for java.lang.reflect:Java Bean

Description

convert Map to Java Bean

Demo Code


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

import java.util.Map;

public class Main {
    /**//from w  w  w.  j  a  v  a 2s. c o  m
     * ?Map?Bean
     *
     * @param map
     * @param obj
     * @return
     */
    public static Object convertMap2Bean(Map<String, String> map, Object obj) {
        Class clazz = obj.getClass();

        Field[] fields = clazz.getDeclaredFields();
        for (Field field : fields) {
            String fieldName = field.getName();
            String propertyName = fieldName;
            String value = map.get(propertyName);
            try {
                field.setAccessible(true);
                field.set(obj, value);
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

        }
        return obj;
    }
}

Related Tutorials