RSS Entries RSS
RSS Subscribe by Email

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();
	}
Share and Enjoy:
  • Add to favorites
  • HackerNews
  • DZone
  • Reddit
  • del.icio.us
  • StumbleUpon
  • Slashdot
  • Digg
  • Google Bookmarks
  • Facebook

Tags:

3 Comments »

  1. 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

  2. Ivana said,

    October 5, 2009 at 1:18 pm

    Very neat solution Paul, thank you!

  3. 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

RSS feed for comments on this post · TrackBack URL

Leave a Comment