• map2bean & bean2map


    1,自己实现;
    
    /**
     * @author xx
     * @since 2020/7/8
     */
    @Slf4j
    public class JavaBeanUtils {
    
        /**
         * 实体类转map
         * 效率较低
         *
         * @param obj
         * @return
         */
        public static Map<String, Object> convertBeanToMap(Object obj) {
            if (obj == null) {
                return null;
            }
            Map<String, Object> map = new HashMap<String, Object>(16);
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor property : propertyDescriptors) {
                    String key = property.getName();
                    // 过滤class属性
                    if (!key.equals("class")) {
                        // 得到property对应的getter方法
                        Method getter = property.getReadMethod();
                        Object value = getter.invoke(obj);
                        if (null == value) {
                            map.put(key, "");
                        } else {
                            map.put(key, value);
                        }
                    }
                }
            } catch (Exception e) {
                log.error("convertBean2Map Error:", e);
            }
            return map;
        }
    
    
        /**
         * map 转实体类
         *
         * @param clazz
         * @param map
         * @param <T>
         * @return
         */
        public static <T> T convertMapToBean(Class<T> clazz, Map<String, Object> map) {
            T obj = null;
            try {
                BeanInfo beanInfo = Introspector.getBeanInfo(clazz);
                // 创建 JavaBean 对象
                obj = clazz.newInstance();
                // 给 JavaBean 对象的属性赋值
                PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
                for (PropertyDescriptor descriptor : propertyDescriptors) {
                    String propertyName = descriptor.getName();
                    if (map.containsKey(propertyName)) {
                        // 下面一句可以 try 起来,这样当一个属性赋值失败的时候就不会影响其他属性赋值。
                        Object value = map.get(propertyName);
                        if ("".equals(value)) {
                            value = null;
                        }
                        Object[] args = new Object[1];
                        args[0] = value;
                        descriptor.getWriteMethod().invoke(obj, args);
                    }
                }
            } catch (IllegalAccessException e) {
                log.error("convertMapToBean 实例化JavaBean失败 Error:", e);
            } catch (IntrospectionException e) {
                log.error("convertMapToBean 分析类属性失败 Error:", e);
            } catch (IllegalArgumentException e) {
                log.error("convertMapToBean 映射错误 Error:", e);
            } catch (InstantiationException e) {
                log.error("convertMapToBean 实例化 JavaBean 失败 Error:", e);
            } catch (InvocationTargetException e) {
                log.error("convertMapToBean字段映射失败 Error:", e);
            } catch (Exception e) {
                log.error("convertMapToBean Error:", e);
            }
            return (T) obj;
        }
    
        /**
         * 将map通过反射转化为实体
         *
         * @param map
         * @param obj
         * @return
         * @throws Exception
         */
        public static Object mapToModel(Map<String, Object> map, Object obj) throws Exception {
            if (!map.isEmpty()) {
                for (String key : map.keySet()) {
                    Object value = null;
                    if (!key.isEmpty()) {
                        value = map.get(key);
                    }
                    Field[] fields = null;
                    fields = obj.getClass().getDeclaredFields();
                    String clzName = obj.getClass().getSimpleName();
                    for (Field field : fields) {
                        int mod = field.getModifiers();
                        if (field.getName().toUpperCase().equals(key.toUpperCase())) {
                            field.setAccessible(true);
                            //进行类型判断
                            String type = field.getType().toString();
                            if (Objects.isNull(value)) {
                                continue;
                            }
                            if (type.endsWith("String")) {
                                value = value.toString();
                            }
                            if (type.endsWith("Date")) {
                                value = new Date(value.toString());
                            }
                            if (type.endsWith("Boolean")) {
                                value = Boolean.getBoolean(value.toString());
                            }
                            if (type.endsWith("int")) {
                                value = new Integer(value.toString());
                            }
                            if (type.endsWith("Long")) {
                                value = new Long(value.toString());
                            }
                            field.set(obj, value);
                        }
                    }
                }
            }
            return obj;
        }
    
        /**
         * 实体对象转成Map
         *
         * @param obj 实体对象
         * @return
         */
        public static Map<String, Object> object2Map(Object obj) {
            Map<String, Object> map = new HashMap<>(16);
            if (obj == null) {
                return map;
            }
            Class clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();
            try {
                for (Field field : fields) {
                    field.setAccessible(true);
                    map.put(field.getName(), field.get(obj));
                }
            } catch (Exception e) {
                log.error("object2Map Error:", e);
            }
            return map;
        }
    
        /**
         * Map转成实体对象
         *
         * @param map   map实体对象包含属性
         * @param clazz 实体对象类型
         * @return
         */
        public static Object map2Object(Map<String, Object> map, Class<?> clazz) {
            if (map == null) {
                return null;
            }
            Object obj = null;
            try {
                obj = clazz.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) {
                log.error("map2Object Error:", e);
            }
            return obj;
        }
    
    
        public static void main(String[] args) {
    
            Student s = new Student();
            s.setUserName("ZHH");
            s.setUserName2("ZHH");
            s.setUserName3("ZHH");
            s.setUserName4("ZHH");
            s.setUserName5("ZHH");
            s.setDate(new Date());
            s.setAge(24);
            long sss = System.currentTimeMillis();
            System.out.println("==" + object2Map(s));
            long ddd = System.currentTimeMillis();
            //0ms
            System.out.println(ddd - sss);
    
            Map<String, Object> map = new HashMap<>(4);
            map.put("userName", "zhh");
            map.put("userName2", "zhh");
            map.put("userName3", "zhh");
            map.put("userName4", "zhh");
            map.put("userName5", "zhh");
            map.put("age", 24);
            map.put("date", new Date());
    
            long aaa = System.currentTimeMillis();
            System.out.println("++" + map2Object(map, Student.class));
            long www = System.currentTimeMillis();
            //0ms
            System.out.println(www - aaa);
    
            long q = System.currentTimeMillis();
            System.out.println("==22++" + convertBeanToMap(s));
            long f = System.currentTimeMillis();
            //16ms
            System.out.println(f - q);
    
            try {
    //            DateTime parse = DateUtil.parse(new Date().toString());
    //
    //            System.out.println("date:" + parse);
            } catch (Exception e) {
                e.printStackTrace();
            }
    
            long c = System.currentTimeMillis();
            System.out.println("==22++" + convertBeanToMap(s));
            long d = System.currentTimeMillis();
            //0ms
            System.out.println(d - c);
    
    
            long a = System.currentTimeMillis();
            System.out.println("++22==" + convertMapToBean(Student.class, map));
            long b = System.currentTimeMillis();
            //0ms
            System.out.println(b - a);
    
            try {
                long start = System.currentTimeMillis();
                System.out.println("++3333333==" + mapToModel(map, new Student()).toString());
                long end = System.currentTimeMillis();
                //0ms
                System.out.println(end - start);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    
    }
    
    
    2,也可以直接使用Hutool提供的MapUtil实现
    

      

  • 相关阅读:
    1、一条sql查询语句的执行过程
    go 内存分配
    GO Json
    gorm CRUD:读写数据
    go 基于切片的队列实现
    go的错误处理
    grpc
    sqlalchemy 判断字段是否存在
    定时函数
    用Python获取Linux资源信息的三种方法
  • 原文地址:https://www.cnblogs.com/hbuuid/p/13265494.html
Copyright © 2020-2023  润新知