map 转换 实体类 方法

public static   T mapToEntity(Map map, Class entity) {
        if (null == map){
            return null;
        }
        T t = null;
        try {
            t = entity.newInstance();
            for(Field field : entity.getDeclaredFields()) {
                if (map.containsKey(field.getName())) {
                    boolean flag = field.isAccessible();
                    field.setAccessible(true);
                    Object object = map.get(field.getName());
                    if (object!= null && field.getType().isAssignableFrom(object.getClass())) {
                        field.set(t, object);
                    }
                    field.setAccessible(flag);
                }
            }
            return t;
        } catch (InstantiationException e) {
            logger.error("convert error ", e);
        } catch (IllegalAccessException e) {
            logger.error("convert error ", e);
        }
        return t;
    }

好了 完事

你可能感兴趣的:(java)