Thursday, June 26, 2008

Java : Iterating and printing out elements of objects

It's a common problem.

You have an object aa with variables bb, cc and dd and for logging and for debugging purposes, you want to print out the current values of all three so you have:

System.out.println ("value of bb is " +;
System.out.println ("value of cc is " +;

which gets tedious when it's a large object.

Reflection to the rescue!

import java.lang.reflect.Field;

Field[] fields = aa.getClass().getDeclaredFields();

for (int i = 0; i < fields.length; i++)
System.out.println (fields[i].getName() + " = " + fields[i].get(xicmd));

catch (Exception ex)
System.out.println ("Reflection exception = " + ex.getMessage());

Note that if the variables in the object are declared as "private", this code will throw an exception. Hence the:


method which overrides this.


No comments: