1.傳入一個List對象,及該對象的屬性名獲取該List中所有該屬性的值(屬性類型為String)
private static List<String> getWybsListValueByName(String fieldName, List list) { try { List<String>lists=new ArrayList<>(list.size()); for (Object object:list) { String firstCode = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstCode + fieldName.substring(1); Method method = object.getClass().getMethod(getter); Object value = method.invoke(object); lists.add(value.toString()); } return lists; } catch (Exception e) { return null; } }
獲取某個對象全部屬性及屬性值映射成map
public static Map getDataList(test test,Object o) throws NoSuchMethodException, InvocationTargetException, IllegalAccessException { Map<String,Object>map=new HashMap<>(); Field[] declaredFields = o.getClass().getDeclaredFields(); for (Field declaredField : declaredFields) { String s = declaredField.toGenericString(); while (s.contains(".")) { s = s.substring(s.indexOf(".") + 1); } String name=s; //get方法list s = "get" + s.substring(0, 1).toUpperCase() + s.substring(1); Object value = o.getClass().getMethod(s).invoke(o); map.put(name,value); } System.out.println("result ======"+map); return map; }