通过Java的反射机制,可以获得当前类中的方法或者当前实体的方法和实体的具体的每个值,这个非常灵活,我暂时领悟到这里。
object是个对象
Field[] fields = object.getClass().getDeclaredFields(); 返回一个属性的数组
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); //取值的方法