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 }
java model 转 Map<String,Object>
原文:https://www.cnblogs.com/sunxun001/p/13156727.html