1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65
| public class FieldUtil { public static final Logger log = LoggerFactory.getLogger(FieldUtil.class);
/** * 根据属性名获取属性值 */ public static Object getFieldValueByName(String fieldName, Object o) { try { String firstLetter = fieldName.substring(0, 1).toUpperCase(); String getter = "get" + firstLetter + fieldName.substring(1); Method method = o.getClass().getMethod(getter, new Class[]{}); Object value = method.invoke(o, new Object[]{}); return value; } catch (Exception e) { log.error(e.getMessage(), e); return null; } }
/** * 获取属性名数组 */ public static String[] getFiledName(Object o) { Field[] fields = o.getClass().getDeclaredFields(); String[] fieldNames = new String[fields.length]; for (int i = 0; i < fields.length; i++) { System.out.println(fields[i].getType()); fieldNames[i] = fields[i].getName(); } return fieldNames; }
/** * 获取属性类型(type),属性名(name),属性值(value)的map组成的list */ public static List<Map<String,Object>> getFiledsInfo(Object o) { Field[] fields1 = o.getClass().getDeclaredFields(); Field[] fields2 = o.getClass().getSuperclass().getDeclaredFields(); Field[] fields = new Field[fields1.length + fields2.length]; fields = ArrayUtil.append(fields1, fields2); String[] fieldNames = new String[fields.length]; List<Map<String, Object>> list = new ArrayList<>(); Map<String, Object> infoMap = null; for (Field field : fields) { infoMap = new HashMap<>(); infoMap.put("type", field.getType()); infoMap.put("name", field.getName()); infoMap.put("value", getFieldValueByName(field.getName(), o)); list.add(infoMap); } return list; }
/** * 获取对象的所有属性值,返回一个对象数组 */ public static Object[] getFiledValues(Object o) { String[] fieldNames = getFiledName(o); Object[] value = new Object[fieldNames.length]; for (int i = 0; i < fieldNames.length; i++) { value[i] = getFieldValueByName(fieldNames[i], o); } return value; } }
|