Java 中 List<Map<String,Object>> 转换 List<javaBean> 详解

javaee 专栏收录该内容
2 篇文章 0 订阅

1.Javabean的实体类

/**
 * 实体类
 * @author suny
 * @date 2017-7-4
 * <pre>
 *  desc:
 * </pre>
 */
public class Person {
    private Long id;

    private String name;

    private String idcard;

    private String address;

    private String homeaddfress;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getIdcard() {
        return idcard;
    }

    public void setIdcard(String idcard) {
        this.idcard = idcard;
    }

    public String getAddress() {
        return address;
    }

    public void setAddress(String address) {
        this.address = address;
    }

    public String getHomeaddfress() {
        return homeaddfress;
    }

    public void setHomeaddfress(String homeaddfress) {
        this.homeaddfress = homeaddfress;
    }

    @Override
    public String toString() {
        return "Person [id=" + id + ", name=" + name + ", idcard=" + idcard
                + ", address=" + address + ", homeaddfress=" + homeaddfress
                + "]";
    }

}

2.List< Map< String,Object>形式的集合

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 测试数据类
 * @author suny
 * @date 2017-7-4
 * <pre>
 *  desc:
 * </pre>
 */
public class PersonData {

    public static List<Map<String, Object>> datas() {
        List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
        Map<String, Object> map = new HashMap<String, Object>();

        map.put("ID", 1L);
        map.put("NAME", "per11");
        map.put("IDCARD", "icard111");
        map.put("ADDRESS", "add1111");
        map.put("HOMEADDFRESS", "homeadd11111");
        list.add(map);

        Map<String, Object> map1 = new HashMap<String, Object>();
        map1.put("ID", 2L);
        map1.put("NAME", "per22");
        map1.put("IDCARD", "icard222");
        map1.put("ADDRESS", "add2222");
        map1.put("HOMEADDFRESS", "homeadd22222");
        list.add(map1);

        return list;
    }
}

3.获取到的List<Map>结果集转化为JavaBean工具类

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
 * 获取到的List<Map>结果集转化为JavaBean工具类
 * @author suny
 * @date 2017-7-4
 * <pre>
 *  desc:
 * </pre>
 */
public class BeanUtils<T> {

    /**
     * 根据List<Map<String, Object>>数据转换为JavaBean数据
     * @param datas 
     * @param beanClass
     * @return
     * @throws CommonException
     */
    public List<T> ListMap2JavaBean(List<Map<String, Object>> datas, Class<T> beanClass) throws CommonException  {
        // 返回数据集合
        List<T> list = null;
        // 对象字段名称
        String fieldname = "";
        // 对象方法名称
        String methodname = "";
        // 对象方法需要赋的值
        Object methodsetvalue = "";
        try {
            list = new ArrayList<T>();
            // 得到对象所有字段
            Field fields[] = beanClass.getDeclaredFields();
            // 遍历数据
            for (Map<String, Object> mapdata : datas) {
                // 创建一个泛型类型实例
                T t = beanClass.newInstance();
                // 遍历所有字段,对应配置好的字段并赋值
                for (Field field : fields) {
                    if(null != field) { 
                // 全部转化为大写
            String dbfieldname = field.getName().toUpperCase();
                        // 获取字段名称
                        fieldname = field.getName();
                        // 拼接set方法
            methodname = "set" + StrUtil.capitalize(fieldname);
                        // 获取data里的对应值
                        methodsetvalue = mapdata.get(dbfieldname);
                        // 赋值给字段
                        Method m = beanClass.getDeclaredMethod(methodname, field.getType());
                        m.invoke(t, methodsetvalue);
                    }
                }
                // 存入返回列表
                list.add(t);
            }
        } catch (InstantiationException e) {
            throw new CommonException(e, "创建beanClass实例异常");
        } catch (IllegalAccessException e) {
            throw new CommonException(e, "创建beanClass实例异常");
        } catch (SecurityException e) {
            throw new CommonException(e, "获取[" + fieldname + "] getter setter 方法异常");
        } catch (NoSuchMethodException e) {
            throw new CommonException(e, "获取[" + fieldname + "] getter setter 方法异常");
        } catch (IllegalArgumentException e) {
            throw new CommonException(e, "[" + methodname + "] 方法赋值异常");
        } catch (InvocationTargetException e) {
            throw new CommonException(e, "[" + methodname + "] 方法赋值异常");
        }
        // 返回
        return list;
    }

}

4.自定义异常类以及处理字符串的工具类
自定义异常类:

/**
 * 公共异常类
 * 备注:与原异常没有区别,只是多了一个errormsg字段,保存开发人员提供的异常提示信息
 * @author suny
 * @date 2017-7-4
 * <pre>
 *  desc:
 * </pre>
 */
public class CommonException extends Exception {

    // 原始异常
    private Throwable target;

    // 开发提供异常提示内容
    private String errormsg = "";

    public Throwable getTargetException() {
        return target;
    }

    public Throwable getCause() {
        return target;
    }

    protected CommonException() {
        super((Throwable) null);
    }

    public CommonException(Throwable target, String s) {
        super(s, null);
        this.target = target;
        this.errormsg = s;
    }

    public CommonException(Throwable target) {
        super((Throwable) null);
        this.target = target;
    }

    public String getErrormsg() {
        return errormsg;
    }

}

工具类:

/**
 * 字符串工具类
 * @author suny
 * @date 2017-7-4
 * <pre>
 *  desc:创建
 * </pre>
 */
public class StrUtil {

    /**
     * 给第字符串第一个字母大写
     * @param str
     * @return
     */
    public static String capitalize(String str) {
        int strLen;
        if (str == null || (strLen = str.length()) == 0) {
            return str;
        }
        return new StringBuilder(strLen)
            .append(Character.toTitleCase(str.charAt(0)))
            .append(str.substring(1))
            .toString();
    }

    /**
     * 使用StringBuilder拼接字符串
     * @param objects
     * @return
     */
    public static String appendSbl(Object... objects) {
        StringBuilder sbl = new StringBuilder();
        for (Object obj : objects) {
            sbl.append(obj);
        }
        return sbl.toString();
    }

    /**
     * 使用StringBuffer拼接字符串
     * @param objects
     * @return
     */
    public static String appendSbf(Object... objects) {
        StringBuffer sbl = new StringBuffer();
        for (Object obj : objects) {
            sbl.append(obj);
        }
        return sbl.toString();
    }

    /**
     * 根据字符串,获取后缀
     * @param str 
     *      若获取不到,返回 null
     */
    public static String getSuffix(String str) {
        if(null != str && str.lastIndexOf(".") > 0) {
            str = str.substring(str.lastIndexOf("."), str.length());
        } else {
            str = null;
        }
        return str;
    }

}

5.测试类

import com.aisino.bean.Person;
import com.aisino.data.PersonData;
import com.aisino.util.BeanUtils;
import com.aisino.util.CommonException;


/**
 * 测试类
 * @author suny
 * @date 2017-7-4
 * <pre>
 *  desc:
 * </pre>
 */
public class Test {

    /**
     * @param args
     */
    public static void main(String[] args) {
        BeanUtils<Person> beanUtils = new BeanUtils<Person>();
        try {
            System.out.println(beanUtils.ListMap2JavaBean(PersonData.datas(), Person.class));
        } catch (CommonException e) {
            e.printStackTrace();
        }
    }

}
  • 5
    点赞
  • 2
    评论
  • 2
    收藏
  • 一键三连
    一键三连
  • 扫一扫,分享海报

©️2021 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值