Often logging declarations are limited to some important business logic actions. Another interesting logging case is the fully dumping of data objects (beans). It causes more transparence of the data flow in your software system and it enables a way to monitor your system in more detail. An example could be: One endpoint, which you are using, was changed. Now you have sometimes strange exceptions. You suppose that one field value or the combination of field values generates this strange exceptions at the backend. A fast way to identify the failure is dumping of your data objects. Java helps you with aid of the reflection API.
Example (access all fields value and metadata at the toString()-method):
public class CustomerTO {
private String firstName;
private String secondName;
private String phone;
....
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}
public Date getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
...
}
Override the toString() method:
@Override
public String toString() {
try {
String result = "";
Class cls = this.getClass();
result += "[[" + this.getClass().getName() + "[\n";
Field fieldlist[] = cls.getDeclaredFields();
for (int i = 0; i < fieldlist.length; i++) {
Field fld = fieldlist[i];
result += "field [\n";
result += "name = " + fld.getName() + "\n";
result += "type = " + fld.getType() + "\n";
int mod = fld.getModifiers();
result += "modifiers = " + Modifier.toString(mod) + "\n";
fld.setAccessible(true);
result += "value = " + fld.get(this) + "\n";
result += "]\n";
}
result += "]" + "\n";
return result;
} catch (Throwable e) {
e.printStackTrace();
}
return super.toString();
}
Example generates (e.g. on LOG.info(customerTO)) the following output:
[[CustomerTO[ field [ name = firstName type = class java.lang.String modifiers = private value = Rafael ] field [ field [ name = secondName type = class java.lang.String modifiers = private value = Sobek ] ... ]Regards
Rafael Sobek
Technorati Tags: Java Reflection API Dumping Logging Monitoring

Here is a worked example of how to put reflection to good use: http://bytearray.brixtonjunkies.com/2009/09/24/auto-object-population-via-reflection/