1 package com.tirsen.nanning.samples.prevayler; 2 3 import java.lang.reflect.Array ; 4 import java.lang.reflect.Field ; 5 import java.lang.reflect.Modifier ; 6 import java.util.HashSet ; 7 import java.util.Set ; 8 9 import org.apache.commons.logging.Log; 10 import org.apache.commons.logging.LogFactory; 11 12 public class ObjectGraphVisitor { 13 private static final Log logger = LogFactory.getLog(ObjectGraphVisitor.class); 14 protected Set visited = new HashSet (); 15 16 public Set getVisited() { 17 return visited; 18 } 19 20 public static void visit(Object o, ObjectGraphVisitor visitor) { 21 visitor.visited.add(o); 22 visitor.visit(o); 23 } 24 25 protected void visit(Object o) { 26 visitInClass(o.getClass(), o); 27 } 28 29 private void visitInClass(Class aClass, Object o) { 30 if (aClass != null && aClass != Object .class) { 31 visitInClass(aClass.getSuperclass(), o); 32 Field [] fields = aClass.getDeclaredFields(); 33 for (int fieldIndex = 0; fieldIndex < fields.length; fieldIndex++) { 34 visitField(fields[fieldIndex], o); 35 } 36 } 37 } 38 39 protected void visitField(Field field, Object container) { 40 if (!Modifier.isStatic(field.getModifiers())) { 41 field.setAccessible(true); 42 try { 43 Object nested = field.get(container); 44 if (nested != null && nested.getClass().isArray()) { 45 for (int arrayIndex = 0; arrayIndex < Array.getLength(nested); arrayIndex++) { 46 Object arrayNested = Array.get(nested, arrayIndex); 47 visitNested(arrayNested); 48 } 49 } else { 50 visitNested(nested); 51 } 52 53 } catch (IllegalAccessException e) { 54 logger.warn("could not enter field " + field + " on object " + container, e); 55 } 56 } 57 } 58 59 private void visitNested(Object nested) { 60 if (nested != null && !visited.contains(nested)) { 61 visited.add(nested); 62 visit(nested); 63 } 64 } 65 66 } 67 | Popular Tags |