Source of FieldTester.java


  1: import java.lang.reflect.*;
  2: import java.util.*;

  4: /**
  5:    This program shows how to use reflection to print
  6:    the names and values of all nonstatic fields of an object.
  7: */
  8: public class FieldTester
  9: {
 10:    public static void main(String[] args)
 11:          throws IllegalAccessException
 12:    {
 13:       Random r = new Random();
 14:       System.out.print(spyFields(r));
 15:       r.nextInt();
 16:       System.out.println("\nAfter calling nextInt:\n");      
 17:       System.out.print(spyFields(r));
 18:    }

 20:    /**
 21:       Spies on the field names and values of an object.
 22:       @param obj the object whose fields to format
 23:       @return a string containing the names and values of
 24:       all fields of obj
 25:    */
 26:    public static String spyFields(Object obj)
 27:          throws IllegalAccessException
 28:    {
 29:       StringBuffer buffer = new StringBuffer();
 30:       Field[] fields = obj.getClass().getDeclaredFields();
 31:       for (Field f : fields)
 32:       {
 33:          if (!Modifier.isStatic(f.getModifiers()))
 34:          {
 35:             f.setAccessible(true);
 36:             Object value = f.get(obj);
 37:             buffer.append(f.getType().getName());
 38:             buffer.append(" ");
 39:             buffer.append(f.getName());
 40:             buffer.append("=");
 41:             buffer.append("" + value);
 42:             buffer.append("\n");
 43:          }
 44:       }
 45:       return buffer.toString();
 46:    }
 47: }