前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >java基础—-利用注解和反射把map封装成bean

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

作者头像
全栈程序员站长
发布2021-04-07 10:15:27
6680
发布2021-04-07 10:15:27
举报
文章被收录于专栏:全栈程序员必看

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

代码语言:javascript
复制
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;
    }
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2020年11月12日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档