經過Java的反射機制,能夠得到當前類中的方法或者當前實體的方法和實體的具體的每一個值,這個很是靈活,我暫時領悟到這裏。java
object是個對象數組
Field[] fields = object.getClass().getDeclaredFields(); 返回一個屬性的數組ide
Method[] methods = object.getClass().getMethods(); 方法對象
下面放出代碼:用了遞歸遞歸
public static String tt(Object object){ if(object!=null){ String className = object.getClass().getName(); System.out.println("---:"+className); if(className.startsWith("java.util.")){ System.out.println("3---:"+className); List<Object> list = (List<Object>) object; for (Object object2 : list) { tt(object); } }else if(!className.startsWith("java")){ System.out.println("2---:"+className); Field[] fields = object.getClass().getDeclaredFields(); Method[] methods = object.getClass().getMethods(); //獲得類全部屬性 for (int i = 0; i < fields.length; i++) { String propertyName = fields[i].getName(); System.out.println("propertyName:"+propertyName); String propertyGetName = NULL_VALUE; if (propertyName != null && !NULL_VALUE.equals(propertyName)) { propertyGetName = GET+propertyName.toLowerCase(); }else { return null; } //獲取全部方法 for (int j = 0; j < methods.length; j++) { String methodName = methods[j].getName(); if (methodName != null && !NULL_VALUE.equals(methodName)) { methodName = methodName.toLowerCase(); }else { return null; } //執行全部訪問器 if (methodName.equals(propertyGetName)) {//.... try { Object propertyValue = methods[j].invoke(object, null); System.out.println("propertyValue::"+propertyValue); tt(propertyValue); } catch (Exception e) { System.out.println(" >>> get method exception!"); e.printStackTrace(); } } } } } } return null; }
Object propertyValue = methods[j].invoke(object, null); //取值的方法get