title: Generic visitor pattern in java
body: <p>Is the following java implementation of the visitor pattern using generics, general enough to be useful? (I suppose it is). </p>
  
  <p>Could it be improved in some way? It's important to be easily call-able using anonymous classes. Thanks.</p>
  
  <p>(Example of use):</p>
  
  <pre><code>Vector&lt;Number&gt; numbers = new Vector&lt;Number&gt;();
  
          numbers.add(new Double(1.2));
          numbers.add(new Float(-1.2));
          numbers.add(new Double(4.8));
          numbers.add(new Float(-3.4));
          numbers.add(new Long(123456));
          numbers.add(new Short("14"));
  
          For.each(numbers, new Visitor&lt;Number&gt;() {
              public void doIt(Double n) {
                  System.out.println("doIt() for double: " + n);
              }
              public void doIt(Float n) {
                  System.out.println("doIt() for float: " + n);
              }
              public void doIt(Number n) {
                  System.out.println("doIt() for Number: " + n);
              }
          });
  
          Visitor&lt;Number&gt; visi =  new Visitor&lt;Number&gt;() {
              private StringBuffer  all = new StringBuffer ();
              public void doIt(Number n) {
                  System.out.println("doIt() for Number: " + n);
                  all.append(n.toString() + " ");
              }
              public Object getResult () {
                  return all;
              }
          };
  
          For.each(numbers, visi);
  
          System.out.println ("all -&gt; " + visi.getResult());
  </code></pre>
  
  <p>Definitions:</p>
  
  <pre><code>//............................................
  abstract class Visitor&lt;T&gt; {
      public void visit(T n) {
          try {
              this.getClass().getDeclaredMethod("doIt", n.getClass()).invoke(this, n);
          } catch (Exception ex) {
              doIt((T) n);
          }
      }
      public void doIt(T n) {
          System.out.println("doIt() for base " + n);
      }
      public Object getResult() {
          return null;
      }
  } // class
  
  //............................................
  class For {
      public static &lt;T&gt; void each (Collection&lt;T&gt; c, Visitor&lt;T&gt; f) {
          for (T v : c) {
              f.visit(v);
          }
      } // ()
  } // class
  </code></pre>