001package horstmann.ch07_reflect2; 002import java.lang.reflect.Field; 003import java.lang.reflect.Modifier; 004import java.util.Random; 005 006/** 007 This program shows how to use reflection to print 008 the names and values of all nonstatic fields of an object. 009 */ 010public class FieldTester 011{ 012 public static void main(String[] args) 013 throws IllegalAccessException 014 { 015 Random r = new Random(); 016 System.out.print(spyFields(r)); 017 r.nextInt(); 018 System.out.println("\nAfter calling nextInt:\n"); 019 System.out.print(spyFields(r)); 020 } 021 022 /** 023 Spies on the field names and values of an object. 024 @param obj the object whose fields to format 025 @return a string containing the names and values of 026 all fields of obj 027 */ 028 public static String spyFields(Object obj) 029 throws IllegalAccessException 030 { 031 StringBuilder buffer = new StringBuilder(); 032 Field[] fields = obj.getClass().getDeclaredFields(); 033 for (Field f : fields) 034 { 035 if (!Modifier.isStatic(f.getModifiers())) 036 { 037 f.setAccessible(true); 038 Object value = f.get(obj); 039 buffer.append(f.getType().getName()); 040 buffer.append(" "); 041 buffer.append(f.getName()); 042 buffer.append("="); 043 buffer.append("" + value); 044 buffer.append("\n"); 045 } 046 } 047 return buffer.toString(); 048 } 049}