Easy Java Bean toString() using BeanUtils
07/10/2008
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 is very helpful for just such occasions. Thanks to Paul Wilton who suggested this updated code snippet in the comments below.
public String toString() {
return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
}
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
Very neat solution Paul, thank you!
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