01: import java.lang.reflect.*;
02: import java.util.*;
03:
04: /**
05: This program shows how to use reflection to print
06: the names and values of all fields of an object.
07: */
08: public class FieldTest
09: {
10: public static void main(String[] args)
11: throws IllegalAccessException
12: {
13: String input = "Hello, World!";
14: StringTokenizer tokenizer = new StringTokenizer(input, ",");
15: System.out.print(spyFields(tokenizer));
16: tokenizer.nextToken();
17: System.out.println("\nAfter calling nextToken:\n");
18: System.out.print(spyFields(tokenizer));
19: }
20:
21: /**
22: Spies on the field names and values of an object.
23: @param obj the object whose fields to format
24: @return a string containing the names and values of
25: all fields of obj
26: */
27: public static String spyFields(Object obj)
28: throws IllegalAccessException
29: {
30: StringBuffer buffer = new StringBuffer();
31: Field[] fields = obj.getClass().getDeclaredFields();
32: for (int i = 0; i < fields.length; i++)
33: {
34: Field f = fields[i];
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: return buffer.toString();
45: }
46: }