1 Reply Latest reply: Jan 16, 2010 4:24 PM by jschellSomeoneStoleMyAlias RSS

    traverse object tree from the middle with reflection


      I am new to using reflection in more complex scenarios, and would like some advice.

      If I get back a partial object tree, from an ORM layer for example, where I have a series of associated objects, for example Employee, which has a Department attribute, linking it to its parent department, and a collection of child address objects, is it possible to traverse all objects attached to Employee, calling a given method on them, if they extend a certain class?

      Could someone show an example of doing this, or describe how it could be done?

      Thanks for your help.
        • 1. Re: traverse object tree from the middle with reflection
          You have an arbritrarily complex hierarchial collection whith a unknown structure.
          You wish to apply a method to all references in the tree.
          There are only two basic storage mechanisms in java; reference or array.

          Setup: Keep a hashtable/dictionary of each visited reference to avoid endless recursion.

          Method, called Doit() which takes an Object 'n'
          - If n is null return
          - if n is already in hashtable return
          - Add to hashtable
          - if n is of type base class then call target method (might want to decide about thrown exception.)
          - reflect through n for members which are either Object or array (base type Object)
          - If single member is Object then call Doit
          - If array recurse through each item and call Doit()