February 19, 2008

Generic toString() using reflection

We can use this method to print the fields and their corresponding values in any object that implements it. This may be useful for debugging.

/**
* This method prints the details of this object
*/
public String toString() {
StringBuffer buffer = new StringBuffer( 512 );
buffer.append( "+++ " + this.getClass().getName() + "\n" );
java.lang.reflect.Field[] fields = this.getClass().getDeclaredFields();

for ( int i = 0; i < fields.length; i ) {
try {
buffer.append( " " + fields[i].getName() + ": " fields[i].get(this) + "\n" );
}
catch (Exception e) {
}
}
return buffer.toString();
}

No comments: