Thursday, April 28, 2011

Easy Java Bean toString() using BeanUtils

Its always good to write toString() function for the bean, but doing it manually is really tedious for lazy developers, where one concatenates the fields in the 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();

1 comment: