January 8th, 2010
7:40 pm
Debug Logging of Bean properties

Posted under Java
Tags , , ,

A useful tool for doing this is the apache.commons.lang.builder.ToStringBuilder using one of the reflectionToString method flavours which are designed for this job. You can easily create dumps of entity beans and bean collections with this, and you can choose the output format.

Whilst it is tempting to override the toString methods on e.g. all your entity beans, as this will automatically dump all related beans & collections just by calling toString on a parent bean, this is not recommended! It can easily cause a storm of toString calls to propagate across all the related beans, resulting in an almost instant stack overflow! This post details how to do this using the apache BeanUtils describe method, and the comments take credit for pointing me in the direction of the apache.commons.lang.ToStringBuilder. However, both methods cause stack overflows when used with JSF and JPA, even when you are not doing any logging.

A better way is to provide a utility method into which you pass any bean or collection, and get the dump string returned which you can then log. The following is an example of a utility class to do this :-

package uk.co.salientsoft.util.beans;
import java.util.Collection;
import org.apache.commons.lang.builder.ToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

public class BeanUtil {

  private static final ToStringStyle defaultStyle = ToStringStyle.SHORT_PREFIX_STYLE;

  public static <E> String dumpProperties(Collection<E> coll) {
    return dumpProperties("", coll, defaultStyle);
  }
  public static <E> String dumpProperties(String prompt, Collection<E> coll) {
    return dumpProperties(prompt, coll, defaultStyle);
  }
  public static <E> String dumpProperties(Collection<E> coll, ToStringStyle style) {
    return dumpProperties("", coll, style);
  }
  public static <E> String dumpProperties(String prompt, Collection<E> coll,
                                          ToStringStyle style) {
    String properties = prompt;
    for (E e : coll) {
     /* Use the apache.commons.lang.builder toStringBuilder
      * to list all this bean's properties
      */
     properties += "\n" + ToStringBuilder.reflectionToString(e, style);
    }
    return properties;
  } 

  public static <E> String dumpProperties(E e) {
    return dumpProperties("", e, defaultStyle);
  }
   public static <E> String dumpProperties(String prompt, E e) {
     return dumpProperties(prompt, e, defaultStyle);
   }
   public static <E> String dumpProperties(E e, ToStringStyle style) {
     return dumpProperties("", e, style);
   }
   public static <E> String dumpProperties(String prompt, E e, ToStringStyle style) {
     return prompt + ToStringBuilder.reflectionToString(e, style);
   }
}

No Comments »