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();
	}

Buy Me a Beer

Share and Enjoy:
  • DZone
  • del.icio.us
  • StumbleUpon
  • Reddit
  • Furl
  • Slashdot
  • Digg
  • Google Bookmarks
  • Technorati
  • Facebook

Tags:

1 Comment »

  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

RSS feed for comments on this post · TrackBack URL

Leave a Comment