01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package horstmann.ch07_reflect2;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Random;

/**
   This program shows how to use reflection to print
   the names and values of all nonstatic fields of an object.
 */
public class FieldTester
{
  public static void main(String[] args)
      throws IllegalAccessException
  {
    Random r = new Random();
    System.out.print(spyFields(r));
    r.nextInt();
    System.out.println("\nAfter calling nextInt:\n");
    System.out.print(spyFields(r));
  }

  /**
      Spies on the field names and values of an object.
      @param obj the object whose fields to format
      @return a string containing the names and values of
      all fields of obj
   */
  public static String spyFields(Object obj)
      throws IllegalAccessException
  {
    StringBuilder buffer = new StringBuilder();
    Field[] fields = obj.getClass().getDeclaredFields();
    for (Field f : fields)
    {
      if (!Modifier.isStatic(f.getModifiers()))
      {
        f.setAccessible(true);
        Object value = f.get(obj);
        buffer.append(f.getType().getName());
        buffer.append(" ");
        buffer.append(f.getName());
        buffer.append("=");
        buffer.append("" + value);
        buffer.append("\n");
      }
    }
    return buffer.toString();
  }
}