• java model 转 Map<String,Object>


     1 import java.lang.reflect.Field;
     2 import java.lang.reflect.InvocationTargetException;
     3 import java.lang.reflect.Method;
     4 import java.lang.reflect.Modifier;
     5 import java.util.ArrayList;
     6 import java.util.Arrays;
     7 import java.util.HashMap;
     8 import java.util.List;
     9 import java.util.Map;
    10 /**
    11  * model工具类
    12  * @author huhj
    13  *
    14  */
    15 public class ModelUtils {
    16  
    17     /**
    18      * 将model转化为map
    19      * @param model
    20      * @return
    21      */
    22     public static Map<String, Object> modelToMap(Object model) {
    23         if (model == null) {
    24             return new HashMap<String, Object>();
    25         }
    26         Map<String, Object> map = new HashMap<String, Object>();
    27         Method method;
    28         Field[] fields1 = model.getClass().getSuperclass().getDeclaredFields(); // 超类属性
    29         Field[] fields2 = model.getClass().getDeclaredFields(); // 本类属性
    30         List<Field> list = new ArrayList<Field>(Arrays.asList(fields1));
    31         List<Field> list2 = Arrays.asList(fields2);
    32         list.addAll(list2);
    33         for (Field field : list) {
    34             boolean isStatic = Modifier.isStatic(field.getModifiers());
    35             if(isStatic) {
    36                 continue;    //去除静态成员
    37             }
    38             String getMethodName = getMethodName(field.getName());
    39             try {
    40                 method = model.getClass().getMethod(getMethodName);
    41                 map.put(field.getName(), method.invoke(model));
    42             } catch (NoSuchMethodException | SecurityException e) {
    43                 e.printStackTrace();
    44             } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
    45                 e.printStackTrace();
    46             }
    47         }
    48         return map;
    49     }
    50  
    51     private static String getMethodName(String name) {
    52         if (name != null && name.length() > 2) {
    53             return "get" + name.substring(0, 1).toUpperCase() + name.substring(1);
    54         }
    55         return name;
    56     }
    57  
    58 }
  • 相关阅读:
    asp.net 使用urlrewrite之后的form postback
    WebService来获取Context.User.Identity.Name为空的问题?
    求救:C#的一个绘图问题
    flex 使用webservice的域访问问题
    请教大家一个问题,有关于数据库的设计
    C# 中使用结构体
    Discuz Nt 3.0开启Memcached 以及二次开发监控Memcached状态
    Flex 中对xml数据的处理
    Oracle alert log 按天 存放 脚本
    Asktom Oracle:On Caching and Evangelizing SQL
  • 原文地址:https://www.cnblogs.com/sunxun001/p/13156727.html
Copyright © 2020-2023  润新知