Map 转换成 Bean,使用反射实现

需要这么一个功能,上网搜到三种实现。

一种需要导入 org.apache.commons.beanutils,还得改 pom。算了吧。

还一种用 内省 实现的,发现不好用。这种方法只支持 map 的 key 是小写字母开头的,例如 userId。如果 key 是大写字母开头的,例如 UserId,转换结果的 value 就是 null 了。

还一种是用 反射 实现的,好使。

调用方法 User u1 = mapToObject( map, User.class );

    /**
     * Map 转换成 Bean,使用反射实现
     */
    public static <T> T mapToObject(Map<String, Object> map, Class<T> beanClass) {
        if ( map == null ) {
            return null;
        }

        T obj = null;

        try {
            obj = beanClass.newInstance();

            Field[] fields = obj.getClass().getDeclaredFields();
            for (Field field : fields) {
                int mod = field.getModifiers();
                if (Modifier.isStatic(mod) || Modifier.isFinal(mod)) {
                    continue;
                }

                field.setAccessible(true);
                field.set(obj, map.get(field.getName()));
            }
        } catch ( Exception e ) {
            e.printStackTrace();
        }

        return obj;
    }

猜你喜欢

转载自blog.csdn.net/beguile/article/details/81566380