一个辅助对象,用于给属性排序
class KeyValue implements Comparable<KeyValue>{ String key; Object value; @Override public int compareTo(KeyValue another) { return this.key.compareTo(another.key); } }
两个函数:
/** * get a series of object's properties * @param obj * @return */ private String getObjectProperties(Object obj) { Field[] fields=obj.getClass().getDeclaredFields(); //String[] fieldNames=new String[fields.length]; List<KeyValue> kvList=new ArrayList<KeyValue>(fields.length); for(int i=0;i<fields.length;i++){ KeyValue kv=new KeyValue(); kv.key=fields[i].getName(); kv.value=getFieldValueByName(kv.key,obj); kvList.add(kv); } Collections.sort(kvList); StringBuilder sb=new StringBuilder(); int idx=0; for(KeyValue kv:kvList) { idx++; sb.append("#"+idx+","+kv.key+","+kv.value+" "); } return sb.toString(); } /** * get property value of a object * @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; } }
调用效果:
#1,connectPointCode,10005 #2,connectPointDetailCode,1 #3,createdDatetime,2019-12-03 14:54:48.248 #4,createdUser,BatchUser #5,deliveryDate,Tue Dec 03 14:54:48 JST 2019 #6,errorCount1,null #7,errorCount2,null #8,errorCount3,null #9,interfaceCode,00001 #10,ioCount1,0 #11,ioCount2,null #12,ioCount3,null #13,ioStatus,1 #14,processCount,23 #15,updatedDatetime,2019-12-03 14:54:48.248 #16,updatedUser,BatchUser #17,userDataParam01,AllocationReq_10005_20191127163829.csv #18,userDataParam02,0 #19,userDataParam03,null #20,userDataParam04,null #21,userDataParam05,null #22,userDataParam06,null #23,userDataParam07,null #24,userDataParam08,null #25,userDataParam09,null #26,userDataParam10,null
感谢: