title: Java polymorphism and downcasting
body: <p>I am playing with Java's reflection API, and I'm writing methods that inspect a given object and describes its fields, methods, and so on.</p>
  
  <p>I am using the <code>getFields()</code> method to iterate on the different attributes and display the object contents:</p>
  
  <pre><code>public static void display(Integer i)
  {
      System.out.println("An integer: " + i);
  }
  
  // Basically a method for each primitive type wrapper
  
  public static void display(Object o)
  {
      for (Field f : c.getFields())
      {
          System.out.println("A " + o.getClass() + " which is composed of:");
          display(f.get(o));
      }
  }
  </code></pre>
  
  <p>(Other primitive types and arrays omitted for simplicity's sake.)</p>
  
  <p>Eventhough <code>Field</code>'s <code>get</code> method returns an <code>Object</code>, I thought the right methods would be called for the primitive type wrappers (Integers, Strings, etc.), but actually, only <code>display(Object o)</code> is called (no implicit downcasting is performed).</p>
  
  <p>For now, the only solution I have found is to brutally downcast the objects if possible like this:</p>
  
  <pre><code>public static void display(Object o)
  {
      if (o instanceof Integer)
      {
          display((Integer) o);
          return;
      }
      else if (o instanceof String 
      {
          ... 
      } // And so on
  
      for (Field f : c.getFields())
      {
          System.out.println("A " + o.getClass() + " which is composed of:");
          display(f.get(o));
      }
  }
  </code></pre>
  
  <p>This does however seem ugly, and I was wondering if there was a more elegant way to make sure the right method is called.
  Any ideas?</p>
  
  <p>Thanks in advance, good people from StackOverflow!</p>