1 5 package org.exoplatform.commons.debug; 6 7 import java.util.* ; 8 import java.lang.reflect.Field ; 9 15 public class ObjectDebuger { 16 static public void printObject(Object o) throws Exception { 17 System.out.println(asString(o)) ; 18 } 19 20 static public String asString(Object o) { 21 StringBuffer b = new StringBuffer () ; 22 try { 23 Map map = new HashMap(100) ; 24 if(o instanceof Collection) printCollection(map, (Collection)o, b, "") ; 25 else if(o instanceof Map) printCollection(map, ((Map)o).values(), b, "") ; 26 else printObject(map, o, b, "") ; 27 } catch (Exception ex) { 28 ex.printStackTrace() ; 29 b.append("\n").append(ex.getMessage()) ; 30 } 31 return b.toString() ; 32 } 33 34 static private void printObject(Map printedObjects, Object o, StringBuffer b, String indent) throws Exception { 35 if(o == null) return ; 36 if(printedObjects.containsKey(o)) return ; 37 printedObjects.put(o, o) ; 38 Class clazz = o.getClass() ; 39 Field [] fields = clazz.getDeclaredFields() ; 40 b.append(indent).append("object: " + getClassName(clazz)).append("\n") ; 41 indent = indent + " " ; 42 for(int i = 0; i < fields.length; i++) { 43 if(fields[i].getDeclaringClass().getName().startsWith("java")) continue ; 44 Class type = fields[i].getType() ; 45 fields[i].setAccessible(true); 46 if(type.equals(String .class)) { 47 String s = (String )fields[i].get(o) ; 48 if(s == null) s = "" ; 49 if(s.length() > 50 ) s = s.substring(0, 50) + "...\n" ; 50 b.append(indent).append(fields[i].getName()).append(": ").append(s).append("\n") ; 51 } else if(type.equals(Boolean .class) || type.equals(Boolean.TYPE) || 52 type.equals(Integer .class) || type.equals(Integer.TYPE) || 53 type.equals(Long .class) || type.equals(Long.TYPE) || 54 type.equals(Float .class) || type.equals(Float.TYPE) || 55 type.equals(Double .class) || type.equals(Double.TYPE)) { 56 Object value = fields[i].get(o) ; 57 b.append(indent).append(fields[i].getName()).append(": ").append(value).append("\n"); 58 } else { 59 Object value = fields[i].get(o) ; 60 if(value instanceof Collection) { 61 b.append(indent).append(fields[i].getName()).append("[Collection]\n"); 62 printCollection(printedObjects, (Collection) value, b, indent + " ") ; 63 } else if(value instanceof Map) { 64 b.append(indent).append(fields[i].getName()).append("[Map]\n"); 65 printCollection(printedObjects, ((Map)value).values(), b, indent + " ") ; 66 } else { 67 printObject(printedObjects, value, b, indent) ; 68 } 69 } 70 } 71 } 72 73 static private void printCollection(Map printedObjects, Collection c, 74 StringBuffer b, String indent) throws Exception { 75 Iterator i = c.iterator() ; 76 while(i.hasNext()) { 77 Object o = i.next() ; 78 printObject(printedObjects,o, b, indent) ; 79 } 80 } 81 82 static private String getClassName(Class clazz) { 83 String name = clazz.getName() ; 84 int idx = name.lastIndexOf(".") ; 85 if(idx > 0) name = name.substring(idx + 1, name.length()) ; 86 return name ; 87 } 88 } | Popular Tags |