zoukankan      html  css  js  c++  java
  • Map与实体之间转换

    package com.thunisoft.maybee.engine.utils;
    
    import java.lang.reflect.Field;
    import java.lang.reflect.Modifier;
    import java.util.Date;
    import java.util.HashMap;
    import java.util.Map;
    
    public class MapObjUtil {
    
        /**
         * 实体对象转成Map
         *
         * @param obj 实体对象
         * @return
         */
        public static Map<String, Object> object2Map(Object obj) {
            Map<String, Object> map = new HashMap<String, Object>();
            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) {
                e.printStackTrace();
            }
            return map;
        }
    
        /**
         * Map转成实体对象
         *
         * @param map   map实体对象包含属性
         * @param clazz 实体对象类型
         * @return
         */
        public static <T> T map2Object(Map<String, Object> map, Class<T> clazz) {
            if (map == null) {
                return null;
            }
            T 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);
                    String filedTypeName = field.getType().getName();
                    if (filedTypeName.equalsIgnoreCase("java.util.date")) {
                        String datetimestamp = String.valueOf(map.get(field.getName()));
                        if (datetimestamp.equalsIgnoreCase("null")) {
                            field.set(obj, null);
                        } else {
                            field.set(obj, new Date(Long.parseLong(datetimestamp)));
                        }
                    } else {
                        field.set(obj, map.get(field.getName()));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            return obj;
        }
    }
    
  • 相关阅读:
    lightoj-1047
    lightoj-1044
    lightoj-1045
    lightoj-1082
    LeetCode偶尔一题 —— 19. 删除链表的倒数第N个节点
    Python 3.52官方文档翻译 http://usyiyi.cn/translate/python_352/library/index.html 必看!
    Python3 time模块
    JavaScript CSS 等前端推荐
    Python之 七级字典查询
    将Sublime Text 3设置为Python全栈开发环境(转一个链接)
  • 原文地址:https://www.cnblogs.com/hfultrastrong/p/9075947.html
Copyright © 2011-2022 走看看