zoukankan      html  css  js  c++  java
  • 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 }
  • 相关阅读:
    POJ 2175 Evacuation Plan 费用流 负圈定理
    POJ 2983 Is the Information Reliable? 差分约束
    codeforces 420B Online Meeting
    POJ 3181 Dollar Dayz DP
    POJ Ant Counting DP
    POJ 1742 Coins DP 01背包
    中国儒学史
    产品思维30讲
    Java多线程编程核心技术
    编写高质量代码:改善Java程序的151个建议
  • 原文地址:https://www.cnblogs.com/sunxun001/p/13156727.html
Copyright © 2011-2022 走看看