title: Java toString() using reflection?
body: <p>I was writing a toString() for a class in Java the other day by manually writing out each element of the class to a String and it occurred to me that using reflection it might be possible to create a generic toString() method that could work on ALL classes. I.E. it would figure out the field names and values and send them out to a String.</p>
  
  <p>Getting the field names is fairly simple, here is what a co-worker came up with:</p>
  
  <pre><code>public static List initFieldArray(String className) throws ClassNotFoundException {
  
      Class c = Class.forName(className);
      Field field[] = c.getFields();
      List&lt;String&gt; classFields = new ArrayList(field.length);
  
      for (int i = 0; i &lt; field.length; i++) {
          String cf = field[i].toString();
          classFields.add(cf.substring(cf.lastIndexOf(".") + 1));
      }
  
      return classFields;
  }
  </code></pre>
  
  <p>Using a factory I could reduce the performance overhead by storing the fields once, the first time the toString() is called. However finding the values could be a lot more expensive.</p>
  
  <p>Due to the performance of reflection this may be more hypothetical then practical. But I am interested in the idea of reflection and how I can use it to improve my everyday programming.</p>