Easy Java Bean toString() using BeanUtils
I often want to have a String description of my beans for debugging or logging purposes, but hate having to manually concatenate the fields in my class to create a toString() method. This code snippet using Apache Commons (a.k.a. Jakarta Commons) is very helpful for just such occasions:
public String toString() {
try {
return BeanUtils.describe(this).toString();
} catch (Exception e) {
Logger.getLogger(this.getClass()).error("Error converting object to String", e);
}
return super.toString();
}
Tags: Java
Paul Wilton said,
April 30, 2009 at 1:44 am
I think a much easier and better solution would be simply to use the Commons Lang ReflectionToStringBuilder class:
for example:
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
}
see:
http://commons.apache.org/lang/api/org/apache/commons/lang/builder/ReflectionToStringBuilder.html
Ivana said,
October 5, 2009 at 1:18 pm
Very neat solution Paul, thank you!
Rick said,
October 19, 2009 at 10:44 am
While I enjoyed this tip and implemented it originally, I came across a potential (but very likely) bug with using your original suggestion as it often causes a stackoverflow exception. Paul’s suggestion seems to be better suited. See http://commons.apache.org/beanutils/api/org/apache/commons/beanutils/BeanUtilsBean.html#describe%28java.lang.Object%29