获取属性名称:
/** * 获取属性名数组 * * @param o 对象 * @return 属性名称 */ private String[] getFiledName(Object o){ Field[] fields=o.getClass().getSuperclass().getDeclaredFields(); String[] fieldNames=new String[fields.length]; for(int i=0;i<fields.length;i++){ fieldNames[i]=fields[i].getName(); } return fieldNames; }
根据属性名称获取属性值
/** * 根据属性名获取属性值 * * @param fieldName 属性名称 * @param o 对象 * @return 属性值 */ private 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) { return null; } }
打印属性名及属性值
public void testFiled() { CrmConflictCustomerRespVo object = getObject(); CrmConflictCustomerRespVo object1 = getObject(); String[] fieldNames = getFiledName(object); long startTime = System.currentTimeMillis(); for(int j=0 ; j<fieldNames.length ; j++){ //遍历所有属性 String name = fieldNames[j]; //获取属性的名字 Object value = getFieldValueByName(name,object); Object value1 = getFieldValueByName(name,object1); System.out.println("name = " + name + "; value =" + value + "; value1 = " + value1); } System.out.println("耗时:" + (System.currentTimeMillis() - startTime)); }
标签:return,String,Object,获取,fieldName,Java,属性 From: https://www.cnblogs.com/abel-he/p/17014771.html