|
| 1 | +package v1chap05.objectAnalyzer; |
| 2 | + |
| 3 | +import java.lang.reflect.Array; |
| 4 | +import java.lang.reflect.Field; |
| 5 | +import java.lang.reflect.Modifier; |
| 6 | +import java.util.ArrayList; |
| 7 | +import java.lang.reflect.AccessibleObject; |
| 8 | + |
| 9 | +/** |
| 10 | + * Convert an object to a string represtation that lists all fields. |
| 11 | + * @author Code |
| 12 | + * |
| 13 | + */ |
| 14 | + |
| 15 | +public class ObjectAnalyzer { |
| 16 | + private ArrayList<Object> visited = new ArrayList<>(); |
| 17 | + |
| 18 | + public String toString(Object obj) { |
| 19 | + if(obj == null) return "null"; |
| 20 | + if(visited.contains(obj)) return "..."; |
| 21 | + visited.add(obj); |
| 22 | + Class cl = obj.getClass(); |
| 23 | + if(cl == String.class) return (String) obj; |
| 24 | + if(cl.isArray()) { |
| 25 | + String r = cl.getComponentType() + "[]{"; |
| 26 | + for(int i = 0; i < Array.getLength(obj); i++) { |
| 27 | + if(i > 0) r += ","; |
| 28 | + Object val = Array.get(obj, i); |
| 29 | + if(cl.getComponentType().isPrimitive()) r += val; |
| 30 | + else r += toString(val); //递归 |
| 31 | + } |
| 32 | + return r + "}"; |
| 33 | + } |
| 34 | + |
| 35 | + String r =cl.getName(); |
| 36 | + //inspect the fields of this class and superclass |
| 37 | + do { |
| 38 | + r += "["; |
| 39 | + Field[] fields = cl.getDeclaredFields(); |
| 40 | + //屏蔽Java语言的访问检查,使对象的私有属性也可以被查询设置 |
| 41 | + AccessibleObject.setAccessible(fields, true); |
| 42 | + //get the names and values of all fields |
| 43 | + for(Field f: fields) { |
| 44 | + if(!Modifier.isStatic(f.getModifiers())) { |
| 45 | + if(!r.endsWith("[")) r += ","; |
| 46 | + r += f.getName() + "="; |
| 47 | + try { |
| 48 | + Class t = f.getType(); |
| 49 | + Object val = f.get(obj); |
| 50 | + if(t.isPrimitive()) r += val; |
| 51 | + else r +=toString(val); |
| 52 | + } |
| 53 | + catch (Exception e) { |
| 54 | + e.printStackTrace(); |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + r += "]"; |
| 59 | + cl = cl.getSuperclass(); |
| 60 | + } |
| 61 | + while(cl != null); |
| 62 | + return r; |
| 63 | + } |
| 64 | +} |
0 commit comments