`

将一个 Map 对象转化为一个 JavaBean

阅读更多
/**
     * 将一个 Map 对象转化为一个 JavaBean 使用时最好保证value值不为null 不支持枚举类型和 用户自定义类
     * @param type 要转化的javabean
     * @param map 包含属性值的map map的key值为javabean属性 key值小写
     * @return 转化出来的 JavaBean 对象
     * @throws Exception  Exception
     */
    @SuppressWarnings("unchecked")
    public Object convertMap(Class type, Map<Object, Object> map)
            throws Exception
    {
        // 创建 JavaBean 对象
        Object obj = null;
 
            // 获取类属性
            BeanInfo beanInfo = Introspector.getBeanInfo(type);

            obj = type.newInstance();

            // 给 JavaBean 对象的属性赋值
            PropertyDescriptor[] propertyDescriptors = beanInfo
                    .getPropertyDescriptors();
            for (int i = 0; i < propertyDescriptors.length; i++)
            {
                PropertyDescriptor descriptor = propertyDescriptors[i];
                String propertyName = descriptor.getName().toLowerCase(
                        Locale.getDefault());

                if (map.containsKey(propertyName))
                {
                    String value = ConvertUtils.convert(map.get(propertyName));
                    Object[] args = new Object[1];
                    args[0] = ConvertUtils.convert(value, descriptor
                            .getPropertyType());

                    descriptor.getWriteMethod().invoke(obj, args);

                }
            }
        return obj;
    }
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics