java基础----利用注解和反射把map封装成bean

利用注解可以解决属性名和map键值不匹配的问题

public class mapToBean {
    public static void main(String[] args) {
        Map<String,Object> map=new HashMap<>();
        map.put("empno",35232);
        map.put("ename","张三");
        map.put("job","工作");
        Employee employee = mapToBean(map, Employee.class);
        System.out.println(employee);


    }
    public static <T> T mapToBean(Map<String,Object> map,Class<T> cls){

        T t=null;
        try {
            //创建实例
             t = cls.newInstance();
            //获取类上的所有字段
            Field[] fields = cls.getDeclaredFields();
            if(fields !=null && fields.length>0){
                //遍历字段数组
                for (Field field : fields) {
                    if(field.isAnnotationPresent(Column.class)){
                        Column annotation = field.getAnnotation(Column.class);
                        if(annotation !=null){
                            //获取值
                            String key = annotation.value();
                            //将注解中的值作为map的键查找map中的值
                            Object value = map.get(key);
                            if(value !=null){
                                //说明map中包含这个注解作为键的值,那么我们就映射到bean中
                                String fieldName = field.getName();
                                //通过内省映射
                                PropertyDescriptor pd=new PropertyDescriptor(fieldName,cls);
                                Method writeMethod = pd.getWriteMethod();
                                writeMethod.invoke(t,value);
                            }
                        }
                    }else {
                        //如果不存在注解,那就用字段名去map中取值
                        String name = field.getName();
                        Object value = map.get(name);
                        if(value !=null){
                            //说明map中包含这个注解作为键的值,那么我们就映射到bean中
                            String fieldName = field.getName();
                            //通过内省映射
                            PropertyDescriptor pd=new PropertyDescriptor(fieldName,cls);
                            Method writeMethod = pd.getWriteMethod();
                            writeMethod.invoke(t,value);
                        }
                    }
                }


            }




        } catch (Exception e) {
            e.printStackTrace();
        }


        return t;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值